简体   繁体   中英

NSNotificationCenter observer is not getting removed?

I have added NSNotificationCenter in viewDidLoad method and removed in viewDidUnload but it's not getting removed. I am following ARC. I have followed few answer but I didn't get luck. I dont have reputation for give comments so posting some thing looks like duplicate. Please don't -ve votes.

Sample code:

- (void)viewDidLoad
{     
    [[NSNotificationCenter defaultCenter ] addObserver:self.containerView
                                              selector:@selector(loadInitialScreen)
                                                  name:CLEARSCREEN_DEPOSIT  
                                                object:NULL];
}

- (void)viewDidUnload
{
    [[NSNotificationCenter defaultCenter] removeObserver:self.containerView
                                                    name:CLEARSCREEN_DEPOSIT 
                                                  object:nil];

}

You should remove the observer either in -viewWillDisappear: , -viewDidDisappear: or in the -dealloc method, depending on your needs. The reason is -viewDidUnload in iOS6+ is never called anymore and before iOS6 it's called when a memory warning is received.

Try to use viewDidDisappear instead viewDidUnload :

-(void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self.containerView
                                                    name:CLEARSCREEN_DEPOSIT object:nil];
    [super viewDidDisappear:animated];
}

viewDidUnload is called (for < iOS 6.0), when a memory warning is received to the application/view controller. It will not be called for removal of the view, for that dealloc is called. But as you are using ARC, you cannot implement dealloc method.

The best bet is to remove the observer in the method loadInitialScreen , if it has to be called only once.

If your notification can be posted multiple times, it's better to remove the observer in viewDidDisappear, but then add observer for the notification in ViewWillAppear

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