如何删除观察者

时间:2013-10-03 09:27:34

标签: iphone ios objective-c nsnotificationcenter addobserver

我有一个启用ARC的项目

viewDidLoad

中添加的观察者很少
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getSipNotification:) name:@"getSipNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(syncExtensionData:) name:@"syncExtensionData" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showLocalNotification:) name:@"showLocalNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outgoingCall:)  name:@"outgoingCall" object:nil]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playRingtone)  name:@"playRingtone" object:nil];

我想删除所有观察者,所以我在 viewDidUnload

中添加了以下行
[[NSNotificationCenter defaultCenter] removeObserver:self];

现在我的问题是,这会删除所有观察者吗?

如果不能怎么做?

更新

如果我想删除一个观察者怎么办呢?

你能帮帮我吗?

4 个答案:

答案 0 :(得分:2)

是的,它会删除所有观察者。

 [[NSNotificationCenter defaultCenter] removeObserver:self];

你可以删除像这样的特定观察者......

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"syncExtensionData" object:nil];

答案 1 :(得分:2)

在我的应用程序中,我使用了此通知:

特定观察者以这种方式删除:

 -(void)viewWillAppear:(BOOL)animated
 {

   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceRotatedFeedBackView:) name:UIDeviceOrientationDidChangeNotification object:nil];

}
-(void)deviceRotatedFeedBackView:(NSNotification*)notification
{
    //right whetever you want
}
 - (void)viewWillDisappear:(BOOL)animated
{

  [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}

可能会对你有所帮助。

答案 2 :(得分:1)

是的,它会删除你班上的所有观察员。

您可以使用以下内容删除单个观察者:

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"getSipNotification" object:nil];

删除个别观察者。

答案 3 :(得分:0)

在iOS6及更高版本中不推荐使用viewDidUnload,因此您的观察者永远不会从iOS6及更高版本的通知中心中删除。要删除单个观察者,请尝试

 - (void)removeObserver:(id)notificationObserver name:(NSString *)notificationName object:(id)notificationSender