首页 > 代码库 > 关联--简单暴力的给对象设置属性

关联--简单暴力的给对象设置属性

关联函数,简单说就是强行给对象设置属性,一般用于给系统类强加属性.

1.通过button传递两个实例对象

UIButton *btn = // 创建按钮,省略..
objc_setAssociatedObject(btn, "firstObject", someObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(btn, "secondObject", otherObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[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.
}

像上面的方法,就是再把button传递到selector的时候,强行给button加了两个属性

步骤:1)设定关联

    objc_setAssociatedObject(btn, "firstObject", someObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    btn:被关联者 firstObject:指向关联对象的指针(一般为一个static字符串),第三个参数:关联的对象实例,第四个参数:关联的方式(有几种,类似设定.h文件属性时候的 assign,retain等)

  2)获取关联对象

      id first = objc_getAssociatedObject(sender, "firstObject");

    参数1:被关联者 参数2:指针

2.当然也可以传递block

  我们经常写button的点击事件,我们可以利用关联/block回调/Category,给button添加一个方法,实现Block直接回调,不写点击事件

  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

 

关联--简单暴力的给对象设置属性