·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> iOS-runtime-objc_setAssociatedObject(关联对象以及传值)

iOS-runtime-objc_setAssociatedObject(关联对象以及传值)

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

例子:

static const char kRePResentedObject;

- (IBAction)doSomething:(id)sender {
  UIAlertView *alert = [[UIAlertView alloc]
                        initWithTitle:@"Alert" message:nil
                        delegate:self
                        cancelButtonTitle:@"OK"
                        otherButtonTitles:nil];
  objc_setAssociatedObject(alert, &kRepresentedObject, 
                           sender,
                           OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  [alert show];
  
}

- (void)alertView:(UIAlertView *)alertView 
clickedButtonAtIndex:(NSInteger)buttonIndex {
  UIButton *sender = objc_getAssociatedObject(alertView, 
                                              &kRepresentedObject);
  self.buttonLabel.text = [[sender titleLabel] text];
}

其中:void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)

上面参数依次为:源对象,关键字(唯一静态变量),关联对象,关联策略

id objc_getAssociatedObject(id object, const void *key)

上面参数依次为:源对象,关键字(唯一静态变量),返回的是关联的对象

这样点击不同的button触发UIAlertView点击事件就能改变相应的button的属性了,很方便