- (void)viewDidLoad
{
[super viewDidLoad];
NSString * overview = @"overview";
self.model= [[DataModel alloc] init];
[self.model setValue:@"searph" forKey:@"stockName"];
[self.model setValue:@"10.0" forKey:@"price"];
[self.model addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
objc_setAssociatedObject(self.model, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);
}
-(IBAction)btnpressed:(id)sender
{
[self.model setValue:@"20.0" forKey:@"price"];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"price"]){
NSLog(@"changeDic = %@",change);
NSString * associatedObject = (NSString *)objc_getAssociatedObject(self.model, &overviewKey);
NSLog(@"associatedObject >>>>>>> %@",associatedObject);
}
}
2014-09-22 23:01:25.470 TestAssociatedObject[61080:60b] changeDic = {
kind = 1;
new = 20;
old = 10;
}
2014-09-22 23:01:25.471 TestAssociatedObject[61080:60b] associatedObject >>>>>>> overview
创建关联:
创建关联要使用到Objective-C的运行时函数:objc_setAssociatedObject来把一个对象与另外一个对象进行关联。
objc_setAssociatedObject(self.model, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);
此方法的四个参数分别为:源对象、关键字、关联的对象、关联策略。
关联策略表明了相关的对象是通过赋值,保留引用还是复制的方式进行关联的;
获取相关联的对象:
NSString * associatedObject = (NSString *)objc_getAssociatedObject(self.model, &overviewKey);
参数分别为:源对象、关键字
断开关联:
断开关联是使用objc_setAssociatedObject函数,传入nil值即可
objc_setAssociatedObject(self.model, &overviewKey, nil, OBJC_ASSOCIATION_RETAIN);