[特別標注,文章首發(fā)在CSDN跟束,也是本人原創(chuàng)渐行,下面放一下地址,主頁地址]
0.閱讀本文前你需要手里掌握一個KVODemo叠骑。
可以仿照關(guān)東升《iOS開發(fā)指南》中的例子(AppObserver的例子)李皇,也可以仿照下面這篇文章里的源碼自己寫一個demo,示例Demo
本文是基于上述兩個Demo的不同之處宙枷,綜合KVO寫法的主要核心掉房,通過上述兩個Demo(兩個都寫了最好)來幫助初學者靈活的掌握KVO。
1.超級簡單四步學會使用KVO
1.1在合適的位置初始化一個觀察者慰丛,觀察者可以是一個自定義的類卓囚,也可以是自己(self)。
觀察者的要點是诅病,里面要含有(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context觀察方法哪亿。
下面給出兩個例子:
1.1.1自定義一個AppObserver的類對象,對象內(nèi)有一個方法睬隶,方法中輸出了觀察對象的名字和新當前的新值。
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context{ ? ?NSLog(@"%@ - %@",keyPath,(NSString *)change[NSKeyValueChangeNewKey]);}
1.1.2這個例子中页徐,觀察方法寫在ViewController里苏潜,觀察變化的值是一個類對象的成員變量的變化,觀察的是@“_auctioneer.money”变勇。
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context{
if ( [keyPathisEqualToString:@"_auctioneer.money"]){
self.moneyPay.text = [NSStringstringWithFormat:@"當前競拍者:%@ - 當前出價: %ld",_auctioneer.name,_auctioneer.money];}}
1.2在發(fā)生變化的頁面添加觀察者
1.2.1以自己的一個成員變量NSString * appStatus為觀察變量恤左,以AppObserver類對象為觀察者并配置路徑贴唇。
self.observer = [AppStatusObservernew];//初始化一個觀察者
//配置觀察路徑
[selfaddObserver:self.observerforKeyPath:@"appStatus"options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOldcontext:nil];
1.2.2以Auctioneer對象的成員為觀察變量,自己為觀察者飞袋,并配置路徑戳气。
_auctioneer = [[Auctioneeralloc]initWithName:@"未開拍"payMoney:1000];
[selfaddObserver:selfforKeyPath:@"_auctioneer.money"options:NSKeyValueObservingOptionNew context:nil];//可以看到觀察者是自己,觀察對象是_auctioneer.money
1.3在合適的地方使得觀察變量發(fā)生改變巧鸭。
1.3.1 在app狀態(tài)改變后瓶您,改變appStatus的值。
- (void)applicationWillResignActive:(UIApplication *)application {
self.appStatus = @"inactive";
}
1.3.2 在點擊鼠標之后纲仍,改變了_auctioneer.name的值呀袱。
- (IBAction)moneyAdd:(id)sender {
_auctioneer.name = @"張老板";
_auctioneer.money +=500;
}
1.4 最后記得Remove觀察者,根據(jù)實際請款填寫Observer和路徑郑叠。
- (void)didReceiveMemoryWarning {
[selfremoveObserver:selfforKeyPath:@"_auctioneer.money"];
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}