我想使用像objc_setAssociatedObject这样的现有机制将数据与UIView相关联。在某处有使用它的例子吗?
在objectiveC中,我找到了这个链接:http://inchoo.net/mobile-development/iphone-development/how-to-add-a-property-via-class-category/
但是没有任何东西。
答案 0 :(得分:9)
您需要为objc_setAssociatedObject:
创建一个P / Invokeenum 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)
然后你会像这样使用它:
var str = new NSString ("object");
var key = new NSObject ();
var value = new NSString ("value");
objc_setAssociatedObject (str.Handle, key.Handle, value.Handle, AssociationPolicy.RETAIN);
现在对象str
将有一个关联的字符串“value”。
要获取值,请执行以下操作:
[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);