Home > DeveloperSection > Forums > Which is the better way to remove self from NSNotificationCenter? Just remove self or remove self from the specific notification name?
Tarun Kumar

Total Post:210

Points:1614
Posted on    July-14-2015 12:43 AM

 iPhone iPhone  Ios  Objective C 
Ratings:


 1 Reply(s)
 452  View(s)
Rate this:

I just want to know: Which is the better way to remove self from NSNotificationCenter in dealloc method? Or is anyone have met different behaviors between the two way?

PS. I just catch a weird thing that when I remove self from notification center by the first way but the object which is dealloced still can recieve the notification, and this call a crash exception of course.

Just remove self by follow code:

 [[NSNotificationCenter  defaultCenter] removeObserver:self];

or remove self from the specific notification name like this:

 [[NSNotificationCenter  defaultCenter] removeObserver:self name:NotificationName object:someObj];

PS. I just catch a weird thing that when I remove self from notification center by the first way but the object which is dealloced still can recieve the notification, and this call a crash exception of course.



Glen Martin
Glen Martin

Total Post:27

Points:191
Posted on    July-14-2015 2:01 AM

[[NSNotificationCenter defaultCenter] removeObserver:self];

that will remove all registrations where the observer is self

 

UIViewController could have its own registrations that it doesn't want removed in viewWillDisappear:. It's unlikely to register for any of the notifications in the public API using addObserver:selector:name:object:, because that would preclude you registering for them in your UIViewController subclass, but it could certainly register for non-public notifications now or in a future version.

A safe way to deregister is to send removeObserver:name:object: once for each registration:

- (void)deregisterForNotifications {

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

[center removeObserver:self name:someNotification object:nil];

object:nil];

}


Modified On Jul-14-2015 02:03:01 AM

Don't want to miss updates? Please click the below button!

Follow MindStick