作者:Love@YR
链接:http://blog.csdn.net/jingqiu880905/article/details/50524016
请尊重原创,谢谢!
addObserver有两种时候会调
一种是广播
发广播的方法:
[[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATIONNAME object:nil userInfo:userinfo];//userinfo是个dictionary
监听广播:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectorName:) name:NOTIFICATIONNAME object:nil];
//收到广播要做的事件
-(void)selectorName:(NSNotification *)notification{
NSDictionary *dic= [notification userInfo];
}
第二种是KVO
per= [[Person alloc] init]; //per是全局的
[per setValue:@"annie" forKey:@"name"];
[per setValue:@"20" forKey:@"age"];
[per addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
//此处的self是谁来监听per的变化,谁来监听在谁那里调回调方法
添加默认的响应回调方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{ //object为per ,keyPath为age
if([keyPath isEqualToString:@"age"])
{
//do something
}
}
监听释放
- (void)dealloc
{
[per removeObserver:self forKeyPath:@"age"]; //kvo的
[NSNotificationCenter defaultCenter]removeObserver:self]; //广播的
[per release];
//[super dealloc];
}