# association **Repository Path**: yahibo/association ## Basic Information - **Project Name**: association - **Description**: 关联对象 objc_setAssociatedObject runtime - **Primary Language**: Objective-C - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2018-06-28 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # ios_association #### 项目介绍 关联对象 objc_setAssociatedObject runtime #### 方法介绍 ``` objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key, id _Nullable value, objc_AssociationPolicy policy) object 关联对象 key 关联对象的关键字 必须是唯一不可变的常量 value 被关联者要关联到object上 policy 关联策略 ``` ``` 1、给对象关联一个属性 objc_setAssociatedObject(array, &array_key, dic, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 2、通过绑定key获取关联对象 NSDictionary *di = objc_getAssociatedObject(array, &array_key); 3、移除关联对象 objc_setAssociatedObject(array, &array_key, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 4、移除所有关联对象 objc_removeAssociatedObjects(array); ``` #### 示例 **创建一个UIButton的分类 给button动态添加一个属性,一个block点击回调方法** ``` UIButton+Property.h 申明 #import typedef void(^ButtonEventBlock)(UIButton *response); @interface UIButton (Property) @property (nonatomic,strong) NSString *ids; @property (nonatomic,strong) ButtonEventBlock clickBlock; @end ``` ``` UIButton+Property.m 实现 #import "UIButton+Property.h" #import const NSString *button_property_ids = @"button_property_ids"; const NSString *button_property_click_event = @"button_property_click_event"; @implementation UIButton (Property) -(instancetype)init{ self = [super init]; if (self) { NSLog(@"初始化"); } return self; } -(instancetype)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { NSLog(@"初始化"); [self addTarget:self action:@selector(clickBtnEvent:) forControlEvents:UIControlEventTouchUpInside]; } return self; } -(void)setIds:(NSString *)ids{ objc_setAssociatedObject(self, &button_property_ids, ids, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } -(NSString *)ids{ return objc_getAssociatedObject(self, &button_property_ids); } -(void)setClickBlock:(ButtonEventBlock)clickBlock{ objc_setAssociatedObject(self, &button_property_click_event, clickBlock, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } -(ButtonEventBlock)clickBlock{ return objc_getAssociatedObject(self, &button_property_click_event); } //击事件中调用方法把点击事件通过代码块传递出去 -(void)clickBtnEvent:(UIButton *)button{ ButtonEventBlock block = [self clickBlock]; if (block) { block(button); } } @end ``` ``` 引入分类调创建分类对象测试属性及回调方法 //关联一个方法,点击事件代码块回调 UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake((self.view.frame.size.width-100)/2, 200, 100, 40)]; button.backgroundColor = [UIColor redColor]; button.ids = @"hibo"; [button setTitle:@"点击" forState:UIControlStateNormal]; [self.view addSubview:button]; button.clickBlock = ^(UIButton *response) { NSLog(@"代码块实现点击事件回调:%@",response.titleLabel.text); }; ``` #### iOS技术讨论QQ群:426760990