为什么不从NSNotificationCenter中删除Observer:addObserverForName:usingBlock get called [英] Why doesn't Remove Observer from NSNotificationCenter:addObserverForName:usingBlock get called
问题描述
我很困惑为什么在以下代码中永远不会删除观察者。在我的viewDidAppear中我有以下内容:
I'm confused on why the observer is never removed in the following code. In my viewDidAppear I have the following:
-(void)viewDidAppear:(BOOL)animated{
id gpsObserver = [[NSNotificationCenter defaultCenter]
addObserverForName:FI_NOTES[kNotificationsGPSUpdated]
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note){
NSLog(@"run once, and only once!");
[[NSNotificationCenter defaultCenter] removeObserver:gpsObserver];
}];
}
观察者永远不会被删除,每次输出语句通知已发出。任何人都可以提供任何指导吗?
The observer never gets removed and the statement is output every time the notification is sent out. Can anyone provide any guidance?
推荐答案
当块被 addObserverForName推送到堆栈上时
When the block is pushed onto the stack by addObserverForName:
the method has not yet returned so gpsObserver is nil (under ARC) or garbage/undefined (not under ARC). Declare the variable using __block
outside and this should work.
__block __weak id gpsObserver;
gpsObserver = [[NSNotificationCenter defaultCenter]
addObserverForName:FI_NOTES[kNotificationsGPSUpdated]
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note){
NSLog(@"run once, and only once!");
[[NSNotificationCenter defaultCenter] removeObserver:gpsObserver];
}];
我添加了__weak以确保没有内存泄漏(根据Matt的回答)。代码未经过测试。
I've added an __weak to ensure there is no memory leak (as per Matt's answer). Code not tested.
这篇关于为什么不从NSNotificationCenter中删除Observer:addObserverForName:usingBlock get called的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!