KVO:(Key-Value-Observer)键值观察者,是观察者设计模式的一种具体实现。
KVO触发机制:一个对象(观察者),监测另一对象(被观察者)的某属性是否发⽣生变 化,若被监测的属性发生的更改,会触发观察者的一个方法(方法名固定,类似代理方法)
KVO使用步骤: 1、注册观察者(为被观察者指定观察者以及被观察属性) 2、实现回调方法 3、触发回调方法(被观察属性发⽣生更改) 4、移除观察者
KVO使⽤用场景:MVC中M与C通信,M发⽣生变化通知C。其中M是被
观察者,C是观察者。
KVO注意事项:观察者销毁之前,移除观察者,否则会出现程序异 常(给已经销毁的对象发送消息)
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@property (nonatomic, retain) Person *person;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 初始化person
self.person = [[Person alloc] init];
_person.name = @"小赛赛";
// 注册监听(observer:监听者;forkeypath:监听的对象的属性,options:监听的属性的值是新还是旧)
[_person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionOld context:@"让self去监听person.name的值"];
}
#pragma mark 当监听的值发生改变时,此方法会被执行
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"监听的属性%@",keyPath);
NSLog(@"被监听者%@",object);
#warning ???????????
NSLog(@"所有状态下属性的值%@",change);
NSLog(@"传递过来的值%@", context);
// NSString *newName = change[NSKeyValueChangeNewKey]; // 可以获取到属性的新值
NSString *oldName = change[NSKeyValueChangeOldKey]; // 可以获取到属性的旧值
if (![[object name] isEqualToString:oldName]) { // 如果新旧值不一样,就走该方法
self.view.backgroundColor = [UIColor colorWithRed:arc4random() %256/255.0 green:arc4random() %256/255.0 blue:arc4random() %256/255.0 alpha:1.0];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)Save:(UIButton *)sender {
_person.name = _textField.text;
}
- (void)dealloc {
[_textField release];
[_person release];
// 注销监听
[_person removeObserver:self forKeyPath:@"name" context:@"让self去监听person.name的值"];
[super dealloc];
}
@end