NSNotificationCenter and NSNotification
Every app has an instance of NSNotificationCenter.
Objects can register with NSNotificationCenter as an observer.
Objects can post notifications to NSNotificatonCenter.
When NSNotificationCenter receives a notification of a matching kind, it will forward these on to the appropriate registered objects.
Notification instances are of type NSNotification.
To register a notification:
NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(openDoor:) name:@"Knock" object:nil];
In this example, the openDoor message is sent to the current object (self) when a notification with name "Knock" is posted, by any object (signified by the last argument being nil).
The following method is triggered when the "Knock" notification arrives:
- (void)openDoor:(NSNotification *)n { id poster = [n object]; NSString *name = [n name]; NSDictionary *extraInformation = [n userInfo]; }
userInfo is a dictionary used to pass additional information.
Example notification:
NSDictionary *info = [NSDictionary dictionaryWithObject:@"Fast" forKey:@"Speed]; NSNotification *notification = [NSNotificationnotificationWithName:@"Knock" object:self userInfo:info]; [[NSNotificationCenter defaultCenter] postNotification:notification];
Remember to unregister registered objects if no longer in use:
- (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; }
















