具体用法一:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *firsrString = @"我是第一个按钮"; // �传入的对象可以是字符串,字典,数组类型
NSString *secondString = @"我是第二个按钮";
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 150, 50)];
[btn setBackgroundColor:[UIColor redColor]];
[btn setTitle:@"按钮传值" forState:UIControlStateNormal];
[self.view addSubview:btn];
objc_setAssociatedObject(btn, "firstObject", firsrString, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(btn, "secondObject", secondString, 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_getAssociatedObject(sender, "secondObject");
NSLog(@"%@--%@", first, second);
}
解释一下:
第一步: 设定关联objc_setAssociatedObject(btn, "firstObject", someObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);第一个参数:btn为被关联者(主体),第二个参数:firstObject为指向关联的对象的指针(一般为一个static字符串),第三个参数:关联的对象实例,第四个对象:关联的方式(有几种,类似设定.h文件属性时候的 assign,retain等)
第二步:得到关联的对象
id first = objc_getAssociatedObject(btn, "firstObject");第一个参数:为被关联者第二个参数:为关联对象的指针。
具体用法二:
tableview 点击 cell上的编辑按钮传值:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
StudioTemplateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StudioTemplateCellID"];
[cell.editButton addTarget:self action:@selector(editClick:) forControlEvents:UIControlEventTouchUpInside];
objc_setAssociatedObject(cell.editButton, @"indexPathKey", indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return cell;
}
- (void)editClick:(UIButton *)btn{
NSIndexPath *index = objc_getAssociatedObject(btn, @"indexPathKey");
NSLog(@"%@", index);
}