將物件附加到另一個現有物件(關聯)
可以將物件附加到現有物件,就像有新屬性一樣。這稱為關聯,允許擴充套件現有物件。當通過類擴充套件新增屬性或以其他方式向現有物件新增其他資訊時,它可用於提供儲存。
一旦取消分配目標物件,執行時將自動釋放關聯的物件。
#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);