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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With