Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use objc_setAssociatedObject in monotouch

Tags:

xamarin.ios

I would like to associate data with a UIView using an existing mechanism like objc_setAssociatedObject. Is there an example of its usage somewhere ?

In objectiveC i found this link: http://inchoo.net/mobile-development/iphone-development/how-to-add-a-property-via-class-category/

But in monotouch nothing.

like image 226
Softlion Avatar asked Jan 17 '26 23:01

Softlion


1 Answers

You need to create a P/Invoke to objc_setAssociatedObject:

enum AssociationPolicy {
    ASSIGN = 0,
    RETAIN_NONATOMIC = 1,
    COPY_NONATOMIC = 3,
    RETAIN = 01401,
    COPY = 01403,
}

[DllImport ("/usr/lib/libobjc.dylib")]
static extern void objc_setAssociatedObject (IntPtr object, IntPtr key, IntPtr value, AssociationPolicy policy)

and then you'd use it like this:

var str = new NSString ("object");
var key = new NSObject ();
var value = new NSString ("value");

objc_setAssociatedObject (str.Handle, key.Handle, value.Handle, AssociationPolicy.RETAIN);

and now the object str will have an associated string "value".

To get the value back do this:

[DllImport ("/usr/lib/libobjc.dylib")]
static extern IntPtr objc_getAssociatedObject (IntPtr object, IntPtr key)

var valueptr = objc_getAssociatedObject (str.Handle, key.Handle);
var value = MonoTouch.ObjCRuntime.Runtime.GetNSObject (valueptr);
like image 195
Rolf Bjarne Kvinge Avatar answered Jan 20 '26 21:01

Rolf Bjarne Kvinge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!