Jump to content

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

m
(Updated first D entry)
Line 649:
#import <objc/runtime.h>
 
static char fooKey;
 
int main (int argc, const char *argv[]) {
@autoreleasepool {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
id e = [[NSObject alloc] init];
 
// set
objc_setAssociatedObject(e, &fooKey, [NSNumber numberWithInt:@1], OBJC_ASSOCIATION_RETAIN);
 
// get
NSNumber *associatedObject = objc_getAssociatedObject(e, &fooKey);
NSLog(@"associatedObject: %@", associatedObject);
 
[e release];}
[pool drain];
return 0;
}</lang>
Line 673 ⟶ 672:
 
int main (int argc, const char *argv[]) {
@autoreleasepool {
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);
 
[e release];}
[pool drain];
return 0;
}</lang>
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.