NSNotificationCenter removeObserver:在dealloc和线程安全中 [英] NSNotificationCenter removeObserver: in dealloc and thread-safety
问题描述
我正在使用ARC,并且在观察者的dealloc
中调用[[NSNotificationCenter defaultCenter] removeObserver:someObserver];
.
I'm using ARC and I'm calling [[NSNotificationCenter defaultCenter] removeObserver:someObserver];
in observer's dealloc
.
请务必在调用此方法(或removeObserver:name:object :)之前 notificationObserver或中指定的任何对象 addObserver:selector:name:object:被释放.
Be sure to invoke this method (or removeObserver:name:object:) before notificationObserver or any object specified in addObserver:selector:name:object: is deallocated.
NSNotificationCenter不保留观察者.
NSNotificationCenter does not retain the observer.
问题1:NSNotificationCenter
是线程安全的吗?
Q1: Is NSNotificationCenter
thread-safe?
以防万一,正在释放观察者(并将观察者从通知中心中删除),并且另一个线程同时发布了通知.
In case, the observer is being deallocated(and removing observer from the notification center) and another thread post a notification at the same time.
我遇到随机崩溃,我怀疑是这种情况.
I encounter random crash and I suspect this is the case.
Q2:这种情况可能吗?
Q2: Is this situation possible?
Q3:是否会导致EXC_BAD_ACCESS
?
Q4:那么,在观察者的dealloc
中调用[[NSNotificationCenter defaultCenter] removeObserver:someObserver];
是否安全?
Q4: Then, is it safe to call [[NSNotificationCenter defaultCenter] removeObserver:someObserver];
in observer's dealloc
?
Q5:如果不安全,应该在哪里打电话给removeObserver:
?
Q5: If it is not safe, where should I call removeObserver:
?
推荐答案
我自己偶然遇到了这个问题:在对象处于发送状态时,我刚收到一个通知(该通知通常发生在主线程中)从后台线程释放的过程.我通过在主线程中执行removeObserver
并等待来解决它:
I just stumbled into this problem myself: I had one notification just in the process of being sent (which always happens in the main thread) while the object was in the process of being deallocated from a background thread. I fixed it by simply performing removeObserver
in the main thread and waiting:
- (void)removeNotificationCenterObserver
{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self];
}
- (void)dealloc
{
[self performSelectorOnMainThread:@selector(removeNotificationCenterObserver) withObject:self waitUntilDone:YES];
}
这将等到当前运行循环周期结束,并在下一个运行循环周期开始时执行此消息.这样可以确保所有仍在运行的功能都可以完成.
This waits until the current run loop cycle ends and executes this message at the beginning of the next run loop cycle. This ensures that any functions that are still running will finish.
这篇关于NSNotificationCenter removeObserver:在dealloc和线程安全中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!