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

例子:

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的属性了,很方便

 

 
posted @ 2015-09-09 01:33  幻想无极  阅读(494)  评论(0编辑  收藏  举报