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

Content added Content deleted
({{omit from|ZX Spectrum Basic}})
No edit summary
Line 314: Line 314:


Here, the two 'variables' can be seen under the single heading 'f'. And of course all of this is done at runtime.
Here, the two 'variables' can be seen under the single heading 'f'. And of course all of this is done at runtime.

=={{header|Objective-C}}==
Objective-C doesn't have the ability to add a variable to an instance at runtime. However, since Mac OS X 10.6 and iOS 3.1, it has something that can accomplish a very similar purpose, called "associative references" or "associated objects", which allow you to attach additional information onto an object without changing its class.

You can put associative references on any object. You can put multiple ones on the same object. They are indexed by a pointer key (typically the address of some dummy variable). You use the functions <code>objc_getAssociatedObject()</code> and <code>objc_setAssociatedObject</code> to get and set them, respectively.

<lang objc>#import <Foundation/Foundation.h>
#import <objc/runtime.h>

char fooKey;

int main (int argc, const char *argv[]) {
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);

return 0;
}</lang>



=={{header|Oz}}==
=={{header|Oz}}==