天天看點

超級簡單四步使用KVO

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];

    } }

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. }