I just learned about NSNotificationCenter. Any class in a program can send a notification message to the notification center, and all classes can listen to the center and respond to messages that apply to it. It’s kind of like a callback, but really not.

This is part of my code for implementing a custom keyboard in my iPhone app.

To send a notification named “keyboardDone” to all objects in your program.

[[NSNotificationCenter defaultCenter] postNotificationName: @"keyboardDone" object: nil];

To listen for the “keyboardDone” notification and call the “keyboardDoneObserver:” method when it’s received this can be added to your class’ init code.

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardDoneObserver:) name: @"keyboardDone" object: nil];

And this is the “keyboardDoneObserver:” method that gets called when notified.

-(void)keyboardDoneObserver: (NSNotification*)notification {
     // do work here

One thought on “NSNotificationCenter

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s