objc_setAssociatedObject

引入头文件
#import 

要关联的对象的键值,一般设置成静态的,用于获取关联对象的值
static char UIButtonKey;

//创建两个需要关联的对象
    UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    button.center = self.view.center;
    button.backgroundColor = [UIColor redColor];
    [self.view addSubview:button];

    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    label.backgroundColor = [UIColor yellowColor];
    label.text =@"获取";
//给对象确立关联(让label关联到button上)    
    objc_setAssociatedObject(button, &UIButtonKey, label, OBJC_ASSOCIATION_RETAIN);

//根据键值获取到关联对象   
    UILabel * lab =  objc_getAssociatedObject(button, &UIButtonKey);
    NSLog(@"lab.text = %@",lab.text);

//断开关联  
    objc_setAssociatedObject(button, &UIButtonKey, nil, OBJC_ASSOCIATION_ASSIGN);
 UILabel * lab1 =  objc_getAssociatedObject(button, &UIButtonKey);
    NSLog(@"断开关联之后的lab1.text = %@",lab.text);

你可能感兴趣的:(objc_setAssociatedObject)