Supports retain/release for Object.

This commit is contained in:
Ritalin 2023-12-30 22:43:35 +09:00
parent 10e552bd37
commit 353986763c

View file

@ -96,8 +96,19 @@ 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;
test {
const testing = std.testing;
const NSObject = objc.getClass("NSObject").?;
@ -108,3 +119,24 @@ test {
try testing.expectEqualStrings("NSObject", obj.getClassName());
obj.msgSend(void, objc.sel("dealloc"), .{});
}
fn retainCount(obj: Object) c_ulong {
return obj.msgSend(c_ulong, objc.Sel.registerName("retainCount"), .{});
}
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"), .{});
}