繁体   English   中英

我是否需要从NSNotificationCenter中删除观察者一次,或者添加多少次观察者?

[英]Do I need to remove an observer from the NSNotificationCenter once, or as many times as it was added?

在我的viewDidLoad ,我将我的控制器添加为两个通知的观察者:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:NetworkStatusChangedNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkLocationStatus:) name:LocationStatusChangedNotification object:nil];

在我的dealloc ,我应该删除一次还是两次? removeObserver方法似乎没有指定特定通知。

[[NSNotificationCenter defaultCenter] removeObserver:self];
[[NSNotificationCenter defaultCenter] removeObserver:self]; // is this required?

您只需要删除一次。

如果需要,还可以使用-removeObserver:name:object:来停止仅观察其中一个通知。

文档是消除疑虑的最佳方式:

The following example illustrates how to unregister someObserver for all 
notifications for which it had previously registered:

[[NSNotificationCenter defaultCenter] removeObserver:someObserver];

来自参考:

RemoveObserver:从接收者的调度表中删除指定给定观察者的所有条目。

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html

所以你只需要调用一次

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM