/*
<p style="color: rgb(51, 51, 51); margin-top: 0px; margin-bottom: 0px; font-stretch: normal; font-size: 21px; font-family: STSong;"><span style="font-stretch: normal; font-family: Times;"><span style="font-size: 18px;">KVO,</span></span><span style="font-size: 18px;">即:</span><span style="font-stretch: normal; font-family: Times;"><span style="font-size: 18px;">Key-Value Observing</span></span><span style="font-size: 18px;">,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。</span></p><p style="color: rgb(51, 51, 51); margin-top: 0px; margin-bottom: 0px; font-stretch: normal; font-size: 21px; font-family: STSong;"><span style="font-size: 18px;">系统框架已经支持KVO,所以程序员在使用的时候非常简单。</span></p><p style="color: rgb(51, 51, 51); margin-top: 0px; margin-bottom: 0px; font-stretch: normal; font-size: 21px; font-family: STSong;"><span style="font-size: 18px;">1. 注册,指定被观察者的属性,</span></p><p style="color: rgb(51, 51, 51); margin-top: 0px; margin-bottom: 0px; font-stretch: normal; font-size: 21px; font-family: STSong;"><span style="font-size: 18px;">2. 实现回调方法</span></p><p style="color: rgb(51, 51, 51); margin-top: 0px; margin-bottom: 0px; font-stretch: normal; font-size: 21px; font-family: STSong;"><span style="font-size: 18px;">3. 移除观察</span></p>
*/
#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(@"%@" ,@"名字修改了");
}
}