Anonymous user
Add a variable to a class instance at runtime: Difference between revisions
Add a variable to a class instance at runtime (view source)
Revision as of 01:02, 3 August 2012
, 11 years ago→{{header|Objective-C}}
m (Omit NetRexx) |
|||
Line 466:
// get
NSNumber *associatedObject = objc_getAssociatedObject(e, &fooKey);
NSLog(@"associatedObject: %@", associatedObject);
[e release];
[pool drain];
return 0;
}</lang>
You can also use a selector as the key, since two selectors with the same content are guaranteed to be equal:
<lang objc>#import <Foundation/Foundation.h>
#import <objc/runtime.h>
int main (int argc, const char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
id e = [[NSObject alloc] init];
// set
objc_setAssociatedObject(e, @selector(foo), [NSNumber numberWithInt:1], OBJC_ASSOCIATION_RETAIN);
// get
NSNumber *associatedObject = objc_getAssociatedObject(e, @selector(foo));
NSLog(@"associatedObject: %@", associatedObject);
|