您的位置:首页 > 编程语言

KVO代码

2015-10-04 14:47 260 查看
// KVO 作用:观察对象的值是否发生变化,可以展示变化前后的值

// 某个对象添加观察者

/*

参数1:self

参数2:观察被观察扎哪一个具体的值发生变化

参数3:取到被观察者变化前及变化后的值

*/

[_dogModel addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];

[_catModel addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew |NSKeyValueObservingOptionOld context:nil];

// 实现KVO的相关方法

// 只要被观察者的值发生变化就执行

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

/*

参数1:被观察的具体值

参数2:被观察者的指针

参数3:变化前以及后的值 key为old的时:变化前的值,可以为new时:变化后的值

参数4:上下文

*/

// 判断被观察者是属于哪个类?

if ([object isKindOfClass:[DogModel class]]) {

NSString * old = [change objectForKey:@"old"];

NSString * new = [change objectForKey:@"new"];

// 展示

_label.text = [NSString stringWithFormat:@"old:%@ new:%@", old, new];

}

else if ([object isKindOfClass:[CatModel class]])

{

NSString * old = [change objectForKey:@"old"];

NSString * new = [change objectForKey:@"new"];

_nextLabel.text = [NSString stringWithFormat:@"old:%@ new:%@",old, new];

}

}

// 注销观察者

- (void)dealloc

{

[_dogModel removeObserver:self forKeyPath:@"name" context:nil];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: