如何使用objc_setAssociatedObject
与对象关联?
OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
答案 0 :(得分:4)
value
必须是Objective-C对象。您需要将结构包装在Objective-C类中。您可以使用NSValue。
StructType s = ...;
NSValue* value = [NSValue valueWithBytes:&s objCType:@encode(StructType)];
objc_setAssociatedObject(obj, SPECIAL_KEY, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
...
NSValue* value = objc_getAssociatedObject(obj, SPECIAL_KEY);
StructType s;
[value getValue:&s];