如何在Obj-C的运行时中将结构与对象相关联

时间:2017-04-21 15:46:08

标签: ios objective-c runtime

如何使用objc_setAssociatedObject与对象关联?

OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)

1 个答案:

答案 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];