NSNotificationCenter 中的addObserver和addObserverForName的释放问题。
(如果释放不对,会出现一次post,收到多次消息的问题)
1.加入观察者
[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWithNote:) name:@"NoteName" object:nil];
2.实现响应
-(void)dealWithNote:(NSNotification *)note {
}
3.推送消息
[[NSNotificationCenter defaultCenter] postNotificationName:@"NoteName" object:nil];
4.释放资源
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"NoteName" object:nil];
而addObserverForName就有些不同了。
1.注册观察者,加入了queue(可传nil)和__block. 这样简化了代码。 例如:
_observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"NoteName"object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
}];
4.释放资源
// 这里不能使用
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"NoteName" object:nil];
而使用一下方式
if(_observer){
[[NSNotificationCenter defaultCenter] removeObserver:_observer];
}