In short, an association function forcibly sets attributes for an object and is generally used to impose attributes on the system class.
1. pass two instance objects through the button
Uibutton * BTN = // create button, omitted .. objc_setassociatedobject (BTN, "firstobject", someobject, callback); values (BTN, "secondobject", otherobject, callback); [BTN addtarget: Self action: @ selector (Click :) forcontrolevents: uicontroleventtouchupinside];-(void) Click :( uibutton *) sender {ID first = objc_getassociatedobject (sender, "firstobject ");
Id second = objc_setassociatedobject (sender, "secondobject"); // etc.
}
Like the above method, when the button is passed to the selector, two attributes are forcibly added to the button.
Step: 1) set Association
objc_setAssociatedObject(btn, "firstObject", someObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
BTN: connected by firstobject: pointer to the correlated object (Generally, it is a static string). The third parameter is the associated object instance, and the fourth parameter is the association method (there are several parameters, such as assign and retain when setting the. h file attribute)
2) Get the associated object
ID first = objc_getassociatedobject (sender, "firstobject ");
Parameter 1: Joined parameter 2: pointer
2. Block can also be passed.
We often write button click events. We can use Association/block callback/category to add a method to the button to implement block direct callback without writing click events.
Uicontrol + blocks. h
#import <UIKit/UIKit.h>#import <objc/runtime.h>typedef void (^ActionBlock)(id sender);@interface UIControl (Blocks)- (void)addEventHandler:(ActionBlock)handler forControlEvents:(UIControlEvents)controlEvents;@end
Uicontrol + blocks. m
#import "UIControl+Blocks.h"static char UIButtonHandlerKey;@implementation UIControl (Blocks)- (void)addEventHandler:(ActionBlock)handler forControlEvents:(UIControlEvents)controlEvents{ objc_setAssociatedObject(self, &UIButtonHandlerKey, handler, OBJC_ASSOCIATION_COPY_NONATOMIC); [self addTarget:self action:@selector(callActionHandler:) forControlEvents:controlEvents];}- (void)callActionHandler:(id)sender{ ActionBlock handler = (ActionBlock)objc_getAssociatedObject(self, &UIButtonHandlerKey); if (handler) { handler(sender); }}@end
Association-simple and violent setting properties for objects