Merge pull request #6 from ritalin/main

Supports retain/release for Object.
This commit is contained in:
Mitchell Hashimoto 2024-01-05 20:43:13 -08:00 committed by GitHub
commit 294e0f3765
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -96,8 +96,23 @@ pub const Object = struct {
const ivar = c.object_getInstanceVariable(self.value, name, null);
c.object_setIvar(self.value, ivar, val.value);
}
pub fn retain(self: Object) Object {
return fromId(objc_retain(self.value));
}
pub fn release(self: Object) void {
objc_release(self.value);
}
};
extern "c" fn objc_retain(objc.c.id) objc.c.id;
extern "c" fn objc_release(objc.c.id) void;
fn retainCount(obj: Object) c_ulong {
return obj.msgSend(c_ulong, objc.Sel.registerName("retainCount"), .{});
}
test {
const testing = std.testing;
const NSObject = objc.getClass("NSObject").?;
@ -108,3 +123,20 @@ test {
try testing.expectEqualStrings("NSObject", obj.getClassName());
obj.msgSend(void, objc.sel("dealloc"), .{});
}
test "retain object" {
const testing = std.testing;
const NSObject = objc.getClass("NSObject").?;
const obj = NSObject.msgSend(objc.Object, objc.Sel.registerName("alloc"), .{});
_ = obj.msgSend(objc.Object, objc.Sel.registerName("init"), .{});
try testing.expectEqual(@as(c_ulong, 1), retainCount(obj));
_ = obj.retain();
try testing.expectEqual(@as(c_ulong, 2), retainCount(obj));
obj.release();
try testing.expectEqual(@as(c_ulong, 1), retainCount(obj));
obj.msgSend(void, objc.sel("dealloc"), .{});
}