In the previous chapter, we talked about the extension of class methods. The reference is to add another instance variable (usually a static variable) to the existing class ), this function is only available after IOS and OS X v10.6.
The reason for this mechanism is similar to the method extension of the class.
Static char overviewkey;
Nsarray * array =
[[Nsarray alloc] initwithobjects: @ "one", @ "two", @ "three", nil];
// For the purposes of authentication, use initwithformat: To ensure
// The string can be deallocated
Nsstring * Overview =
[[Nsstring alloc] initwithformat: @ "% @", @ "first three numbers"];
Objc_setassociatedobject (
Array,
& Overviewkey,
Overview,
Objc_association_retain
);
[Overview release];
// (1) Overview valid
[Array release];
// (2) Overview invalid
How to get the value:
# Import <Foundation/Foundation. h>
# Import <objc/runtime. h>
Int main (INT argc, const char * argv []) {
NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init];
Static char overviewkey;
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"];
Objc_setassociatedobject (
Array,
& Overviewkey,
Overview,
Objc_association_retain
);
[Overview release];
Nsstring * associatedobject =
(Nsstring *) objc_getassociatedobject (array, & overviewkey );
Nslog (@ "associatedobject: % @", associatedobject );
Objc_setassociatedobject (
Array,
& Overviewkey,
Nil,
Objc_association_assign
);
[Array release];
[Pool drain];
Return 0;
}