Iphone 我是否需要从NSNotificationCenter中删除观察者一次,或者删除次数与添加次数相同?
在myIphone 我是否需要从NSNotificationCenter中删除观察者一次,或者删除次数与添加次数相同?,iphone,nsnotificationcenter,Iphone,Nsnotificationcenter,在myviewDidLoad中,我将控制器添加为两个通知的观察者: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:NetworkStatusChangedNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selec
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:
停止仅观察其中一个通知。参考:
RemoveObserver:
从接收方的分派表中删除指定给定观察者的所有条目
因此,您只需呼叫它一次是消除疑虑的最佳方式:
The following example illustrates how to unregister someObserver for all
notifications for which it had previously registered:
[[NSNotificationCenter defaultCenter] removeObserver:someObserver];
您还可以使用
removeObserver:name:object:
删除特定通知和/或对象的观察者。如果观察者正在观察其他通知,这将使其留在通知中心。@Jasarien我想你添加了评论,我编辑了我的答案,以便在同一时间说同样的话:)