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:214

Points:1642
Posted by  Tarun Kumar
 767  View(s)
Ratings:
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.

  1. Glen Martin

    Post:27

    Points:191
    Re: Which is the better way to remove self from NSNotificationCenter? Just remove self or remove self from the specific notification name?

    [[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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!