iOS开发7-KVO(Key-Value Observer)键值观察
KVO的全称是Key-Value Observer,即键值观察。是一种没有中心枢纽的观察者模式的实现方式。一个主题对象管理所有依赖于它的观察者对象,并且在自身状态发生改变的时候主动通知观察者对象。
1、注册观察者
Person.h/m
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property(nonatomic,strong)NSString *name;
@end
#import "Person.h"
@implementation Person
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.p =[[Person alloc]init];
self.p.name=@"Sam";
//添加观察者
[self.p addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:@"NameCHange"];
}
2、更改被观察对象属性的值,触发通知
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.p.name=@"Kate";
}
3、处理收到的通知
//处理收到的更改通知
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
//响应观察者
NSLog(@"keyPath=%@",keyPath); //被观察的属性
NSLog(@"object=%@",object); //被观察的对象
NSLog(@"change=%@",change); //改变的值(新的、旧的)
NSLog(@"context=%@",context); //添加观察者时的传值
/*
2015-10-22 19:38:48.651 [4479:351489] keyPath=name
2015-10-22 19:38:48.652 [4479:351489] object=<Person: 0x7f9130528cb0>
2015-10-22 19:38:48.652 [4479:351489] change={
kind = 1;
new = Kate;
old = Sam;
}
2015-10-22 19:38:48.652 [4479:351489] context=NameCHange
*/
<pre name="code" class="objc"> //被观察的对象生命周期结束前移除观察者
//被观察的对象释放掉但观察者还在的话,程序会崩溃
[self.p removeObserver:self forKeyPath:@"name"];
NSLog(@"移除观察者");<span style="font-family: 'Helvetica Neue';"> </span>
}
4、注销观察者
//被观察的对象生命周期结束前移除观察者
//被观察的对象释放掉但观察者还在的话,程序会崩溃
[self.p removeObserver:self forKeyPath:@"name"];
NSLog(@"移除观察者");