Search code examples
iosobjective-cunrecognized-selector

iOS - keyboardWillShow: unrecognized selector sent to instance


In my application I am adding following observer in init method of class A.


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

Then I am extending a class B from class A. keyboardWillShow and keyboardWillHide methods are written in super class i.e. class A. However application throws following exception when I click on some textview to enter text.

terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[B   keyboardWillShow:]: unrecognized selector sent to instance xyz'

It is confuses as methods are already written in the supper class of B. If it is due to invalid arguments, then how can it be as arguments are passing by iOS itself.


Solution

  • It's hard to tell from just that bit of code, but it looks like you have an error in your method names. In the code you provided, you are registering for the notifications with a method named "keyboardWillToggle:". The error is indicating that you are trying to call a "keyboardWillShow:" method, though.

    It would probably be best to declare and implement "keyboardWillShow:" and "keyboardWillHide:" on your class A, and then register for the notifications like this:

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