Skip to content

Instantly share code, notes, and snippets.

@rolfbjarne
Created November 1, 2017 07:14
Show Gist options
  • Save rolfbjarne/62149c28d755ef1f7c22cc76b6196b43 to your computer and use it in GitHub Desktop.
Save rolfbjarne/62149c28d755ef1f7c22cc76b6196b43 to your computer and use it in GitHub Desktop.
using ObjCRuntime;
class Helper {
IntPtr GetObjCIvar (string name)
{
IntPtr native;
object_getInstanceVariable (handle, name, out native);
return native;
}
void SetObjCIvar (string name, NSObject value)
{
// get existing
var existing = GetObjCIvar (name);
if (existing != IntPtr.Zero) {
if (value != null && existing == value.Handle)
return; // setting the same value, just ignore
} else if (value == null) {
return; // both existing and new values are null, just ignore
}
if (value != null)
value.DangerousRetain ();
object_setInstanceVariable (handle, "myProperty", value != null ? value.Handle : IntPtr.Zero);
if (existing != null)
existing.DangerousRelease ();
}
[DllImport ("/usr/lib/libobjc.dylib")]
extern static void object_getInstanceVariable (IntPtr obj, string name, out IntPtr val);
[DllImport ("/usr/lib/libobjc.dylib")]
extern static void object_setInstanceVariable (IntPtr obj, string name, IntPtr val);
}
class Test : NSObject
{
[Export ("myProperty")]
public NSObject MyProperty {
get {
return Runtime.GetNSObject (Helper.GetObjCIvar ("myProperty"));
}
set {
Helper.SetObjCIvar ("myProperty", value);
}
}
public override void Dispose ()
{
// This must be done so that the value's reference count is released
MyObject = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment