1.KVO:Key-Value-Observer/键值观察者,是观察者设计模式的一种具体实现。
KVO触发机制:一个对象(观察者),检测另一对象(被观察者)的某属性是否发生改变,若被检测的属性发生改变,会触发观察者的一个方法。
KVO使用步骤:
1、注册观察者(为被观察者指定观察者以及被观察属性)
2、实现回调方法
3、触发回调方法(被观察者属性发生更改)
4、移除观察者
KVO使用场景:MVC中M与C通信,M发生变化通知C。其中M是被观察者,C是观察者。
KVO注意事项:观察者销毁之前,移除观察者,否则程序会崩溃.
主要代码:
数据模型Person
.h文件
@property(nonatomic,strong) NSString *name;
视图控制器.m文件
@interface ViewController ()
#pragma mark============将Person对象声明为属性
@property(nonatomic,strong) Person *person;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//初始化person对象
self.person = [[Person alloc] init];
self.person.name = @"宋静静";
self.nameLabel.text = _person.name;
#pragma mark================给person对象添加观察者对象(C和M通信)
//1.添加观察者
[self.person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:@"描述"];
}
//2.观察者执行的方法,被观察对象的属性一旦发生改变,立即触发此方法
//keyPath:被观察对象的被观察属性
//object:被观察者对象
//change:被观察对象的属性值
//context:描述,可以用来传值,使用强制转换获取值
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
//NSLog(@"________");
NSLog(@"被观察对象的被观察属性:%@",keyPath);
NSLog(@"%@",object);
NSLog(@"%@",change);
NSLog(@"%@",(__bridge NSString *)context);
//多个观察者存在时,可以根据被观察者对象的类别以及被观察属性作出不同操作
if ([object isKindOfClass:[Person class]] && [keyPath isEqualToString:@"name"]) {
//model对象的属性改变后,更新UI显示数据
//写法一:
//_nameLabel.text = change[@"new"];
//写法二:相当于:NSString *const NSKeyValueChangeNewKey = @"new";
_nameLabel.text = change[NSKeyValueChangeNewKey];
//移除person对象的观察者对象(通常该方法用在播放下一首音乐时)
[self.person removeObserver:self forKeyPath:@"name"];
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
self.person.name = @"宋静";
// self.nameLabel.text = @"宋静";
}