Objective-C extension mechanism-associative

Source: Internet
Author: User

In addition to category, objective-C has an associative extension mechanism.

Category is common and serves to extend some new methods to existing classes.

So associative is something that category cannot do, and attributes can be extended.

Official Document: Objective-C Runtime reference

To use associative, you must first # import <objc/runtime. h>

Then you can use the following method for extension.

OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)    __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key)    __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);OBJC_EXPORT void objc_removeAssociatedObjects(id object)    __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);

Objc_setassociatedobject, objc_getassociatedobject, and objc_removeassociatedobjects are all methods of the OC's external connection.

You can use objc_setassociatedobject to set an attribute. objc_getassociatedobject gets an attribute. objc_removeassociatedobjects deletes an attribute Extended through associative.

The object parameter is used as the object instance to be extended, and the key is used as the attribute key of the object instance. The value is the attribute value of the object instance, and the policy is used as the associated policy. Its enumeration includes:

enum {    OBJC_ASSOCIATION_ASSIGN = 0,    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,    OBJC_ASSOCIATION_RETAIN = 01401,    OBJC_ASSOCIATION_COPY = 01403};typedef uintptr_t objc_AssociationPolicy;

It's easy to understand, that is, assign, retain, and copy.

The code is simple! In this example, several block attributes are extended for the uiview through the category objective to implement the click, double-click, and other events of the uiview.

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.