RosettaCodeData/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-1.m

21 lines
537 B
Mathematica
Raw Permalink Normal View History

2013-04-10 22:43:41 -07:00
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
2015-02-20 00:35:01 -05:00
static void *fooKey = &fooKey; // one way to define a unique key is a pointer variable that points to itself
2013-04-10 22:43:41 -07:00
int main (int argc, const char *argv[]) {
2014-04-02 16:56:35 +00:00
@autoreleasepool {
2013-04-10 22:43:41 -07:00
2014-04-02 16:56:35 +00:00
id e = [[NSObject alloc] init];
2013-04-10 22:43:41 -07:00
2014-04-02 16:56:35 +00:00
// set
2015-02-20 00:35:01 -05:00
objc_setAssociatedObject(e, fooKey, @1, OBJC_ASSOCIATION_RETAIN);
2013-04-10 22:43:41 -07:00
2014-04-02 16:56:35 +00:00
// get
2015-02-20 00:35:01 -05:00
NSNumber *associatedObject = objc_getAssociatedObject(e, fooKey);
2014-04-02 16:56:35 +00:00
NSLog(@"associatedObject: %@", associatedObject);
2013-04-10 22:43:41 -07:00
2014-04-02 16:56:35 +00:00
}
2013-04-10 22:43:41 -07:00
return 0;
}