Use of IOS associations

Source: Internet
Author: User

Association refers to associating two objects together so that one of the objects is part of another object.

With correlation, we can add storage space to objects without modifying the definition of the class.

Associations are based on keywords, so we can add any number of associations to any object, each with a different keyword.

Create an association

Objc_setassociatedobject 
    1. static char Key;
    2. Nsarray * Array =[[nsarray alloc] initwidthobjects:@"Red" @"green" @"blue", nil];
    3. NSString * string = [[NSString alloc] Initwithformat:@"color"];
    4. Objc_setassociatedobject (Array, &key, String, objc_association_retain);
    5. [String release];
    6. (1) string is still available
    7. [Array release];
    8. (2) string not available

Get Association Object

Objc_getassociatedobject.

    1. NSString * Associatedobject = (NSString *) objc_getassociatedobject (array, &key);

Disconnect Association

objc_setassociatedobject function , you can pass in the nil value.

    1. Objc_setassociatedobject (array, &key, nil, objc_association_assign);

Where the associated object is nil, then the association policy does not matter.


Use the function objc_removeassociatedobjects to disconnect all associations.

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.