// Created by wjn on 15/9/30.
// Copyright © 2015年 wlm. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, retain) NSString *string;
@end
@implementation ViewController
- (void)dealloc {
// 切记一定要在完成之后移除掉 - ARC一样
[self removeObserver:self forKeyPath:@"string"];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 20, self.view.frame.size.width, 40);
[button setTitle:@"KVO" forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor greenColor]];
[button addTarget:self action:@selector(buttonDidPress:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
// KVO 一个类监听自己的属性(成员变量)的变化
// 参数1:观察者
// 参数2:要观察的对象
// 参数3:一旦发生改变,观察的结果是取新值还是旧值
// 参数4:一旦发生改变,可以传递的内容
[self addObserver:self forKeyPath:@"string" options:NSKeyValueObservingOptionNew context:@"BOOM"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
// 系统的方法
// 当观察到的属性改变之后,自动调用这个方法
NSLog(@"%@", keyPath);
NSLog(@"%@", object);
NSLog(@"%@", change);
NSLog(@"%@", context);
}
//-(NSMutableArray *)mutableArray {
// if (!_mutableArray) {
// self.mutableArray = [NSMutableArray arrayWithObject:@"a"];
// }
// return _mutableArray;
//}
- (void)buttonDidPress:(UIButton *)sender {
// [self.mutableArray addObject:@"a"];
[self setValue:@"aa" forKey:@"string"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end