标签:
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@property (nonatomic, strong) Person *model;
@end
@implementation ViewController
- (void)dealloc
{
//第三步:移除观察者 经常会忘记,非常重要 不写的代价就是程序会补丁时间 不定地点的Crash;
//dealloc 在ARC模式下 一定要写
[self.model removeObserver:self forKeyPath:@"name"];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.model = [[Person alloc] init];
self.model.name = @"秦喜军";
// self.model.delegate = self;
//由self 去观察self.model的name属性是否发生了变化 self.model被观察者
//第一步 给一个属性添加一个观察者 去观察被观察者的某一个属性
[self.model addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
self.model.name = @"秦喜君";
}
//- (void)changBankcolor
//{
// self.view.backgroundColor = [UIColor redColor];
//}
// 第二步:重写observeValue方法,去执行属性改变之后想要做的操作
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
self.view.backgroundColor = [UIColor redColor];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
标签:
原文地址:http://www.cnblogs.com/mawenqiang/p/4855867.html