您的位置:首页 > 其它

add observer的两个用法

2016-01-15 15:26 281 查看
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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: