一,概述
KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。
二,使用方法
系统框架已经支持KVO,所以程序员在使用的时候非常简单。
1. 注册,指定被观察者的属性,
2. 实现回调方法
3. 移除观察
三,实例:
#import "ViewController.h"
#import "ZHData.h"
@interface ViewController ()
@property (nonatomic ,strong) ZHData *data;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
ZHData *data = [[ZHData alloc] init];
data.name = @"小陆";
self.data = data;
// 监听 name的属性 的改变,变了的话 就回调方法
[data addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(20, 20, 100, 100);
button.backgroundColor = [UIColor yellowColor];
button.layer.borderWidth = 0.5;
button.layer.borderColor = [UIColor greenColor].CGColor;
[button setTitle:@"点击" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view addSubview:button];
[button addTarget:self action:@selector(buttonTouch) forControlEvents:UIControlEventTouchUpInside];
}
- (void) buttonTouch
{
self.data.name = @"小猪";
NSLog(@"点击按钮");
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"name"]) {
NSLog(@"%@" ,@"名字修改了");
}
}