虽然在类扩展中不能添加实例变量,只能添加方法,不过属性并非实例变量,而是set与get的体现,但是可以通过关联引用向任何对象添加键——值数据,上代码:
@implementation ViewController
static const char kRepresentedObject;
- (IBAction)doSomething:(id)sender {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Alert" message:nil
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
/*
objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy);
id object 关联对象
const void *key 固定的键
id value 对应的值
objc_AssociationPolicy policy 关联策略
*/
objc_setAssociatedObject(alert, &kRepresentedObject,
sender,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[alert show];
}
- (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex {
UIButton *sender = objc_getAssociatedObject(alertView,
&kRepresentedObject);
/*
id objc_getAssociatedObject(id object, const void *key)
id object 关联对象
const void *key 固定键对应的地址
*/
self.buttonLabel.text = [[sender titleLabel] text];
}
objc_removeAssociatedObjects 用来移除关联
总结:关联应用其实就是将两个对象相互关联起来,通过一个固定的键和对象对应另一个对象,只要第一个对象还在就可以通过固定键的对应地址获取到第二个对象信息,由此而来可以在不添加变量,不改变类定义,增加类的空间 有时可以达到和不错的效果