#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
//声明属性
@property(nonatomic,strong)Person *person;
@property (weak, nonatomic) IBOutlet UILabel *nameLable;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.person=[Person new];
self.person.name=@"哇哈哈";
_nameLable.text=self.person.name;
//添加观察者
[self.person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:@"描述"];
}
//观察者执行的方法 :被观察对象的属性一旦改变,立即触发此方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
//keyPath 被观察对象的属性
//object 被观察对象
//change 被观察对象的属性值
//context 描述,可以用来传值,使用强制转化获取值
//多个观察者存在时,可以根据被观察者对象的类别以及被观察属性做出不同的操作
if ([object isKindOfClass:[Person class]] && [keyPath isEqualToString:@"name"]) {
//model 对象的属性改变之后,更新UI显示数据
_nameLable.text=change[@"new"];
//同上,更新数据
// NSString *const NSKeyValueChangeNewKey=@"new";
// _nameLable.text=change[NSKeyValueChangeNewKey];
}
//移除观察者
// [self.person removeObserver:self forKeyPath:@"name"];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
self.person.name=@"娃娃";
}
294

被折叠的 条评论
为什么被折叠?



