简体   繁体   中英

How to remove observer

I have an ARC enabled project

There are few observers added in 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];

I want to remove all observers so I added following line in viewDidUnload

[[NSNotificationCenter defaultCenter] removeObserver:self];

Now my question is, is this remove all observers?

If not how can do it?

UPDATE

If I want to remove a single observer how can do it?

Can you help me please.

Yes, It will remove all observers.

 [[NSNotificationCenter defaultCenter] removeObserver:self];

And you can remove a particular observer like this...

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

In my application i used this notification :

for particular observer remove this way :

 -(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];
}

may be it will helpful to you.

Yes it'll remove all the observers in your class.

You can use following to remove single observer:

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

To remove individual observer.

viewDidUnload is deprecated in iOS6 and later, so Your observer never be removed from notification center in iOS6 and later. To remove single observer try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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