iOS程序猿iOS Developer

超级简单四步学会使用KVO

2016-09-11  本文已影响168人  帅裂苍穹的七爷爷

[特别标注,文章首发在CSDN,也是本人原创,下面放一下地址,主页地址]

0.阅读本文前你需要手里掌握一个KVODemo。

可以仿照关东升《iOS开发指南》中的例子(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的类对象,对象内有一个方法,方法中输出了观察对象的名字和新当前的新值。

- (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在发生变化的页面添加观察者

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在合适的地方使得观察变量发生改变。

1.3.1 在app状态改变后,改变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观察者,根据实际请款填写Observer和路径。

- (void)didReceiveMemoryWarning {

[selfremoveObserver:selfforKeyPath:@"_auctioneer.money"];

[superdidReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

上一篇 下一篇

猜你喜欢

热点阅读