Remove NSNotificationCenter observer

user2014474 picture user2014474 · Feb 2, 2013 · Viewed 11.1k times · Source

I am detecting the showing/hiding of the keyboard by adding this code in the ViewDidLoad:

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(keyboardDidHide:) 
                                             name:UIKeyboardDidHideNotification 
                                           object:nil];

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

At some point though I want to remove these observers, without calling

 [[NSNotificationCenter defaultCenter] removeObserver:self];

because this removes all observers, and I have other observers that I don't want to be removed. How can I remove only those two??

Answer

Yaman picture Yaman · Feb 2, 2013
[[NSNotificationCenter defaultCenter] removeObserver:self 
                                                name:UIKeyboardDidHideNotification 
                                              object:nil];

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