简体   繁体   中英

Observer never gets removed from NSNotificationCenter

I'm adding a view controller as an observer for UIKeyboardWillShowNotification notification.

I have this code in my viewDidLoad :

[[NSNotificationCenter defaultCenter] addObserver:self
                                     selector:@selector(keyboardWillShow:)
                                         name:UIKeyboardWillShowNotification
                                       object:nil];

And in my dealloc :

[[NSNotificationCenter defaultCenter] removeObserver:self];

The observer is not being removed even though dealloc is called when the view controller is closed. So when I open it for the second time, NSNotificationCenter will attempt to notify the old object, which is released, and the app crashes.

I have seen several questions here on StackOverflow about this particular problem, but non of the answers works for me.

I've tried removing the observer in viewWillDisappear and viewDidDisappear but the same problem happens.

I'm using ARC.

Have you tried this exact chunk of code in viewWillDisappear ?

- (void)viewWillDisappear:(BOOL)animated 
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

From your explanation I don't think the problem is with the removal of the observer. Try to trigger the Observer from another viewcontroller. If it's not triggered you'll know the removal is successful and the problem occurs when you are adding the observer the second time.

也许尝试通过指定之前设置的参数name ,如下所示:

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];

Looks like the observer is getting set multiple times. Is your controller inherited from a class which also registers for same notification? That could lead to controller instance getting registered as observer more than once. As a workaround try this, in your controller class where you add the observer,

// Remove as observer first
[[NSNotificationCenter defaultCenter] removeObserver:self];
                                      name:UIKeyboardWillShowNotification
                                      object:nil];
// Then add
[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(keyboardWillShow:)
                                      name:UIKeyboardWillShowNotification
                                      object:nil];

This will ensure that the observer is getting added only once.

Hope that helps!

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

它适用于我

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