0.阅读本文前你需要手里掌握一个KVODemo,可以仿照关东升《iOS开发指南》中的例子(AppObserver的例子),也可以仿照下面这篇文章里的源码自己写一个demo:http://www.cnblogs.com/wengzilin/p/3223770.html
本文是基于上述两个Demo的不同之处,综合KVO写法的主要核心,通过上述两个Demo(两个都写了最好)来帮助初学者灵活的掌握KVO
1.超级简单四部使用KVO(基础使用)
1.1在合适的位置初始化一个观察者,观察者可以是一个自定义的类,也可以是自己(self),观察者的要点是,里面要含有(void)observeValueForKeyPath:(NSString
*)keyPath ofObject:(id)object change:(NSDictionary<NSString
*,id> *)change context:(void
*)context观察方法。下面给出两个例子:
11.1.1自定义一个AppObserver的类对象,对象内有一个方法,方法中输出了观察对象的名字和新当前的新值。
- (void)observeValueForKeyPath:(NSString
*)keyPath ofObject:(id)object change:(NSDictionary<NSString
*,id> *)change context:(void
*)context{
NSLog(@"%@
- %@",keyPath,(NSString *)change[NSKeyValueChangeNewKey]);
}
11.1.2这个例子中,观察方法写在ViewController里,观察变化的值是一个类对象的成员变量的变化,观察的是@“_auctioneer.money”。
- (void)observeValueForKeyPath:(NSString
*)keyPath ofObject:(id)object change:(NSDictionary<NSString
*,id> *)change context:(void
*)context{
if
( [keyPathisEqualToString:@"_auctioneer.money"]){
self.moneyPay.text = [NSStringstringWithFormat:@"当前竞拍者:%@ - 当前出价: %ld",_auctioneer.name,_auctioneer.money];
}
self.moneyPay.text = [NSStringstringWithFormat:@"当前竞拍者:%@ - 当前出价: %ld",_auctioneer.name,_auctioneer.money];
}
}
11.2在发生变化的页面添加观察者
11.2.1以自己的一个成员变量NSString * appStatus为观察变量,以AppObserver类对象为观察者并配置路径。
self.observer
= [AppStatusObservernew];//初始化一个观察者
//配置观察路径
[selfaddObserver:self.observerforKeyPath:@"appStatus"options:NSKeyValueObservingOptionNew
| NSKeyValueObservingOptionOldcontext:nil];
11.2.2以Auctioneer对象的成员为观察变量,自己为观察者,并配置路径。
_auctioneer = [[Auctioneeralloc]initWithName:@"未开拍"payMoney:1000];
[selfaddObserver:selfforKeyPath:@"_auctioneer.money"options:NSKeyValueObservingOptionNew context:nil];//可以看到观察者是自己,观察对象是_auctioneer.money
11.3在合适的地方使得观察变量发生改变。
11.3.1 在app状态改变后,改变appStatus的值。
- (void)applicationWillResignActive:(UIApplication
*)application {
self.appStatus
= @"inactive";
}
11.3.2 在点击鼠标之后,改变了_auctioneer.name的值。
- (IBAction)moneyAdd:(id)sender
{
_auctioneer.name
= @"张老板";
_auctioneer.money
+=500;
}
11.4 最后记得Remove观察者,根据实际请款填写Observer和路径。
- (void)didReceiveMemoryWarning
{
[selfremoveObserver:selfforKeyPath:@"_auctioneer.money"];
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}