将对象附加到另一个现有对象(关联)

可以将对象附加到现有对象,就像有新属性一样。这称为关联,允许扩展现有对象。当通过类扩展添加属性或以其他方式向现有对象添加其他信息时,它可用于提供存储。

一旦取消分配目标对象,运行时将自动释放关联的对象。

#import <objc/runtime.h>

// "Key" for association. Its value is never used and doesn't
// matter. The only purpose of this global static variable is to
// provide a guaranteed unique value at runtime: no two distinct 
// global variables can share the same address.
static char key;

id target = ...;
id payload = ...;
objc_setAssociateObject(target, &key, payload, OBJC_ASSOCIATION_RETAIN);
// Other useful values are OBJC_ASSOCIATION_COPY
// and OBJ_ASSOCIATION_ASSIGN

id queryPayload = objc_getAssociatedObject(target, &key);