Add a variable to a class instance at runtime: Difference between revisions

Content added Content deleted
(jq)
Line 659: Line 659:
#import <objc/runtime.h>
#import <objc/runtime.h>


static void *fooKey = &fooKey; // one way to define a unique key is a pointer variable that points to itself
static char fooKey;


int main (int argc, const char *argv[]) {
int main (int argc, const char *argv[]) {
Line 667: Line 667:


// set
// set
objc_setAssociatedObject(e, &fooKey, @1, OBJC_ASSOCIATION_RETAIN);
objc_setAssociatedObject(e, fooKey, @1, OBJC_ASSOCIATION_RETAIN);


// get
// get
NSNumber *associatedObject = objc_getAssociatedObject(e, &fooKey);
NSNumber *associatedObject = objc_getAssociatedObject(e, fooKey);
NSLog(@"associatedObject: %@", associatedObject);
NSLog(@"associatedObject: %@", associatedObject);