例子:
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的属性了,很方便
时间: 2024-10-29 10:47:47