Attach an object to an existing object (association)

suggest change

It’s possible to attach an object to an existing object as if there were a new property. This is called association and lets you extend existing objects. It can be used to provide storage when adding a property via a category or class extension, or to attach additional information to an existing object.

When the association policy is retain or copy, the associated object is released by the runtime once the target object is deallocated. An assign association is not released.

#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_setAssociatedObject(target, &key, payload, OBJC_ASSOCIATION_RETAIN);
// Other useful values are OBJC_ASSOCIATION_COPY
// and OBJC_ASSOCIATION_ASSIGN

id queryPayload = objc_getAssociatedObject(target, &key);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents