objc_getAssociatedObject, objc_setAssociatedObject

1.使用AssociatedObject必须导入头文件.
随便写一个列子,假如页面上有一个Button和一个Label,点击按钮获取Label上的文字.

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundColor:[UIColor redColor]];
[button setTitle:@"button" forState:UIControlStateNormal];
button.frame = CGRectMake(100, 100, 100, 50);
[self.view addSubview:button];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 200, 100, 50)];
label.backgroundColor = [UIColor greenColor];
label.text = @"label";
[self.view addSubview:label];

objc_setAssociatedObject(button, @"title", label, OBJC_ASSOCIATION_RETAIN);
}
- (void)buttonAction:(UIButton *)sender {
  UILabel *label = objc_getAssociatedObject(sender, @"title");
  NSLog(@"%@", label.text);
}

1.第一个参数: id object : 需要传入的是 : 对象的主分支
2.第二个参数: const void *key : 是一个 static 类型的 关键字,这里根据开发者自身来定义就行(尽量写的有根据一点,避免以后忘记是干啥用的)
3.第三个参数: id value : 传入的是: 对象的子分支
4.第四个参数: objc_AssociationPolicy policy :是当前关联对象的类型 strong,weak,copy (枚举类型:开发者可以点进去看)

你可能感兴趣的:(objc_getAssociatedObject, objc_setAssociatedObject)