objc_setAssociatedObject

引入头文件
#import <objc/runtime>

要关联的对象的键值,一般设置成静态的,用于获取关联对象的值
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);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容