Search code examples
iphonekeyboardkeypressnsnotificationcenter

Capture key press event using NSNotificationCenter


this solution Receive iPhone keyboard events

offers a way to capture the keypress event using notification center.

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil];

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextViewTextDidChangeNotification object: nil];

........

-(void) keyPressed: (NSNotification*) notification
{
  NSLog([[notification object]text]);
}

It works ok, but for every key that is been pressed from the keyboard the keyPressed function gets called 3 times.

Is this normal or am i doing something wrong?

Teo


Solution

  • The notification should only appear once per key pressed. At least that is what I get when testing. The only thing I can think of is that you are calling addObserver:selector:name:object: three times.

    Perhaps you are doing it in several view controllers and forget to call removeObserver:name:object:?

    Or you are calling addObserver:selector:name:object: in a function that gets called several times? viewDidLoad is normally a good place to put code like this.