Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 633
Hesham Avatar asked Nov 12 '22 23:11

Hesham


1 Answers

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.

like image 155
Segev Avatar answered Nov 15 '22 07:11

Segev