NSNotificationCenter for iOS and Mac

Guides | Tutorial By 5 years ago

If you’ve ever needed to have an object with multiple delegates you may have created an array and then added each of your delegates to it. This does work but there’s a simpler way which is much easier to implement. Using the NSNotificationCenter you can have objects subscribe to the events/messages they want to know about and get called whenever that ‘event’ takes place. The Cocoa framework uses this as well, and let’s you subscribe to things such as an app entering the background, changing orientations, when it’s running out of memory and when the keyboard is presented or dismissed.

A good example of where to use the NSNotifcationCenter is for when a user logs in to your app (so objects can change their appearance, display user info, etc etc) and when the user logs out (so objects can release any sensitive information), but is also useful in other situations where many objects are interested in the one event.

To set these up, first create a string notification name, this should be accessible by all objects that either want to observe to or post this notification:

static NSString* SomeEventNotification = @"SomeEventNotification";

Now for each object interested in the event, add it as an observer and implement the desired selector:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someEventMethod:) name:SomeEventNotification object:nil];


- (void) someEventMethod:(NSNotification*) notification
	//	Code

Remember to remove the observer when the object is deallocated:

[[NSNotificationCenter defaultCenter] removeObserver:self];

Now wherever the event takes place, tell the NSNotificationCenter:

[[NSNotificationCenter defaultCenter] postNotificationName:SomeEventNotification object:nil];

If you’re unsure of whether an event is posted to the NSNotificationCenter, you can spy on every notification by omitting the name when adding an observer:

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

Whenever I call the NSNotificationCenter I ask for the defaultCenter. This is the ‘event manager’ shared by most objects on the system. If messages need to be kept hidden from other classes or messages of the same name need to be sent to different objects, you can create your own NSNotificationCenter:

NSNotificationCenter* customNotificationCenter = [[NSNotificationCenter alloc] init];

If you’re developing for the Mac, you get access to the NSDistributedNotificationCenter, which allows events to be sent between completely separate apps (if you ever wondered how Growl worked). iTunes also uses this to send events whenever a song is played. To use this, the methods are exactly the same as the NSNotificationCenter, however you can not create your own private center, and userInfo can’t be a complicated type (for example an NSView from one app can’t be shared to another).