How can I add instance variables to all objects? You can use category to easily add methods to existing classes, but you cannot directly add instance variables. (If you use the look-up table method, you can save your money ). However, since Mac OS X v10.6, the system has provided associative references, which can be easily solved.
I modified the code based on the example in objective-C reference. The focus is on the use of objc_setassociatedobject, where the key is an address rather than a string.
# Import <Foundation/Foundation. h> # import <objc/runtime. h> int main (INT argc, const char * argv []) {@ autoreleasepool {/* seciton 0. key and value */static char overviewkey of associated data; static const char * myownkey = "videoproperty \ 0"; static const char intvaluekey = 'I '; nsarray * array = [[nsarray alloc] initwithobjects: @ "one", @ "two", @ "three", nil]; // For the purposes of authentication, use initwithformat: to Ensure // we get a deallocatable string nsstring * Overview = [[nsstring alloc] initwithformat: @ "% @", @ "first three numbers"]; nsstring * videokeyvalue = @ "this is a video"; nsnumber * intvalue = [[nsnumber alloc] initwithint: 5];/* Section 1. associated data settings */objc_setassociatedobject (array, & overviewkey, Overview, objc_association_retain); [Overview release]; objc_setassociatedobject (array, myownkey, video KeyValue, objc_association_retain); objc_setassociatedobject (array, & intvaluekey, intvalue, objc_association_retain);/* Section 3. link Data Query Section */nsstring * associatedobject = (nsstring *) objc_getassociatedobject (array, & overviewkey); nslog (@ "associatedobject: % @", associatedobject ); nsstring * associatedobject2 = (nsstring *) objc_getassociatedobject (array, myownkey); nslog (@ "video key value is % @", Ssociatedobject2); nsstring * assobject3 = (nsstring *) objc_getassociatedobject (array, & myownkey); If (assobject3) {nslog (@ "won't go here! Assobject3 should be nil! ");} Else {nslog (@" OK. No data is available through the myownkey address! ");} Nsnumber * asskeyvalue = (nsnumber *) objc_getassociatedobject (array, & intvaluekey); nslog (@" int value is % d ", [asskeyvalue intvalue]); /* Section 3. link data cleanup part */trim (array, & overviewkey, nil, objc_association_assign); trim (array, myownkey, nil, objc_association_assign); trim (array, & intvaluekey, nil, objc_association_assign); [array release];} return 0 ;}
* You can use the following command to compile it in the command line:
Clang-O associates-g-x objective-C ++-wall associates. Mm-framework Foundation-lobjc