How to use objc_setAssociatedObject in monochromatic

I would like to bind data to a UIView using an existing mechanism such as objc_setAssociatedObject. Is there an example of using it somewhere?

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

But in monotouch nothing.

+3
source share
1 answer

You need to create a P / Invoke for the objc_setAssociatedObject object:

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 will use it as follows:

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 strwill have the associated string "value".

To return the value back, follow these steps:

[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);
+9
source

All Articles