Notifications

A Notification allows an object to post information, for example a change in state, that can be sent to any object that "subscribes" to those notifications. It's a lot like Twitter.

Here is an example,

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

[NSNotificationCenter defaultCenter] is a central dispatch maintained by the OS.The user can create others if desired. In this case the system itself generates the notification when the orientation of the device changes. The didRotate method will find what the new orientation is and decide what to do,

 -(void) didRotate:(NSNotification*)sender
 {
  UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
  if (deviceOrientation == UIDeviceOrientationLandscapeLeft
  || deviceOrientation == UIDeviceOrientationLandscapeRight).................

The sender argument, of type NSNotification, carries information that may be of use:

  • sender.name, an NSString which is the name of the notification
  • sender.object, the object sending the notification
  • sender.userInfo, an NSDictionary with further information from the sender. May be nil.

There are several ways to post your own notifications. Here is an example of the simplest,

 [[NSNotificationCenter defaultCenter]
   postNotificationName:@"notificationName"
   object:self];

To end the sending of all notifications to this object (self),

 [[NSNotificationCenter defaultCenter] removeObserver:self];

To end the sending of specific notifications to this object,

 [[NSNotificationCenter defaultCenter]
   removeObserver:self
   name:theNotification
   object:theSendingObject];

Either name or object may be nil, in which case it is ignored in deciding which notifications to cease. e.g. if name is nil all notifications from object are ended.

NSNotification Center class reference

NSNotification class reference.