Search code examples
iosnotificationsnsnotificationcenterreceiver

NSnotificationCenter postNotificationName who is the receiver?


The documentation http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html talks of the sender and notification name but where does it mention whom to post this notification to?


Solution

  • You don't post a notification directly to someone. The name of the notification, and sender determine who gets the notification.

    Interested objects can subscribe to a notification. When you post a notification, all subscribers who are listening to a notification by that name will get notified. Actually Cocoa notifications can be tweaked at two levels:

    • notification name (string)
    • sender

    The class documentation illustrates this clearly.

    Here's a little ASCII table from the docs showing who gets notified depending on what notification name and sender were used when created:

    Notification name | Notification sender | Notification set specified
    --------------------------------------------------------------------
    Specified         | Specified           | Notifications with a particular name from a specific sender.
    Specified         | Unspecified         | Notifications with a particular name by any sender.
    Unspecified       | Specified           | Notifications posted by a specific sender.
    Unspecified       | Unspecified         | All notifications.
    

    Unspecified means a nil value was supplied for that field.

    Notifications allows for a loosely coupled design as objects are not tied together in their implementations and can work independently off each other.