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.