Graphics Programs Reference
In-Depth Information
Notifications are instances of
NSNotification
. Every
NSNotification
object has
a name and a pointer back to the object that posted it. When you register as an observer,
you can specify a notification name, a posting object, and the message you want to sent to
you when a qualifying notification is posted.
The following snippet of code registers you for notifications named
LostDog
that have
been posted by any object. When an object posts a
LostDog
notification, you'll be sent
the message
retrieveDog:
.
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self // The object
self
will be sent
selector:@selector(retrieveDog:) //
retrieveDog:
name:@"LostDog"
// when
@"LostDog"
is posted
object:nil];
// by
any object
.
Note that
nil
works as a wildcard in the notification center world. You can pass
nil
as
the
name
argument, which will give you every notification regardless of its name. If you
pass
nil
for the notification name and the posting object, you will get every notification.
The method that is triggered when the notification arrives takes an
NSNotification
object as the argument:
- (void)retrieveDog:(NSNotification *)note
{
id poster = [note object];
NSString *name = [note name];
NSDictionary *extraInformation = [note userInfo];
}
Notice that the notification object may have a
userInfo
dictionary attached to it. This
dictionary is used to pass additional information, like a description of the dog that was
found. Here's an example of an object posting a notification with a
userInfo
dictionary
attached:
NSDictionary *extraInfo = [NSDictionary dictionaryWithObject:@"Fido"
forKey:@"Name"];
NSNotification *note = [NSNotification notificationWithName:@"LostDog"
object:self
userInfo:extraInfo];
[[NSNotificationCenter defaultCenter] postNotification:note];
For a (real-world) example, when a keyboard is coming onto the screen, it posts a
UIKeyboardDidShowNotification
that has a
userInfo
dictionary. This dic-
tionary contains the on-screen region that the newly visible keyboard occupies.
This is important: the notification center keeps strong references to its observers. If the
object doesn't remove itself as an observer before it is destroyed, then the next time a no-