Objective-c Study Notes-Part 7-References

Source: Internet
Author: User

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;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.