Use Association Object (the AssociatedObject) was added UIButton Block Response

In development, give UIButton added click event, it is common practice to such

UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];  
    [button addTarget:self action:@selector(touchButton:) forControlEvents:UIControlEventTouchUpInside];

- (void)touchButton:(id)sender
{

}

By selector in response to button clicks, will affirm the separation button and response method, we can UIButton associated with a block to be processed by AssociatedObject runtime is

First, create a UIButton classification (Category) UIButton + block, add addTouchHandler as UIButton in categories: method

UIButton+block.h

@interface UIButton (block)

- (void)addTouchHandler:(TouchBlock)handler;

@end

UIButton+block.m

static void * TouchBlockKey = &TouchBlockKey;

@implementation UIButton (block)

- (void)addTouchHandler:(TouchBlock)handler
{
    objc_setAssociatedObject(self, TouchBlockKey, handler, OBJC_ASSOCIATION_COPY_NONATOMIC);

    [self addTarget:self action:@selector(touchUpInSide:) forControlEvents:UIControlEventTouchUpInside];


}

-(void)touchUpInSide:(UIButton *)btn{
    TouchBlock block = objc_getAssociatedObject(self, TouchBlockKey);
    if (block) {
        block();
    }
}

@end

Is to achieve the above code, the following code will be explained the method for adding an associated target object, wherein the object source object to the associated key for extracting objects associated value value to be associated to the object policy associated policy objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)








id objc_getAssociatedObject(id object, void *key)
This method is used to obtain the associated object from the object associated with the source object by object Key
Key Key used objc_setAssociatedObject

You can get from here to download the sample code

 

Reproduced in: https: //www.cnblogs.com/pretty-guy/p/5686464.html

Guess you like

Origin blog.csdn.net/weixin_33835690/article/details/93438637