Search code examples
objective-cnsnotifications

Objective-C: Getting notification names from all NSDistributedNotificationCenter notifications?


I'm sure I had a tool that could log all system wide notifications but, not being able to find it, I'm writing my own.

So the documentation says I set up the observer by calling:

- (void)addObserver:(id)notificationObserver
           selector:(SEL)notificationSelector
               name:(NSString *)notificationName
             object:(NSString *)notificationSender

…but I don't want to listen to any one notification or object in particular so I set those values to nil. So far so good, I know when notifications are being broadcast.

But how do I get the names of the unknown notification and senders once they've been received? Is it possible?


Solution

  • From the docs:

    The method specified by notificationSelector must have one and only one argument (an instance of NSNotification).

    Therefore:

    -(void)observerMethod:(NSNotification*)notification
    {
      NSLog( @"%@", notification);
    }
    

    The name is a property of the passed notification. The sender is usually the property object. (It is not really the sender, but if somebody else is the sender, the object will be more interesting.) You can retrieve additional information from the userInfo property.

    BTW, take care: The selector in this example is observerMethod:, not observerMethod (colon included).