假设一个场景,股票的价格显示在当前屏幕上,当股票价格更改的时候,实时显示更新其价格。
添加两个实体类 一个是股票Strock 一个是person
Strock.h
@interface Strock : NSObject
{
NSString *_name;
float _price;
}
@end
Strock.m
-(NSString *)description
{
return [NSString stringWithFormat:@"name:%@,price:%f",_name,_price];
}
person.m
//回调方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"keyPath:%@,object:%@,change:%@",keyPath,object,change);
}
viewController.m
self.person = [[Person alloc]init];
self.strock = [[Strock alloc]init];
//给属性赋值
[self.strock setValue:@"baidu" forKey:@"_name"];
[self.strock setValue:@155 forKey:@"_price"];
//设置person为观察者
[self.strock addObserver:self.person forKeyPath:@"_price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}
//拖进来一个点击 事件 当button点击的时候
- (IBAction)priceClicked:(UIButton *)sender {
NSInteger price = [[self.strock valueForKey:@"_price"]floatValue];
[self.strock setValue:@(price+1) forKey:@"_price"];
}
//移除观察者
-(void)dealloc
{
[self.strock removeObserver:self.person forKeyPath:@"_price" context:nil];
}