KVO
//初始化时,注册观察者,监听属性的变化
-(id)init{
if (self=[super init]) {
[self addObserver:self forKeyPath:@"book" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}
return self;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"name"])
{
//打印旧值,新值
NSLog(@"changed:old->%@;new->%@",[change objectForKey:@"old"],[change objectForKey:@"new"]);
}
}
//最后,重写dealloc方法,移除监听
-(void)dealloc
{
[self removeObserver:self forKeyPath:@"name"];
[super dealloc];
}
NOtification
//注册通知中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(print) name:@"name" object:nil];
//发送通知,注册中心就会调用方法print
[[NSNotificationCenter defaultCenter] postNotificationName:@"name" object:nil userInfo:nil];