1

I can't see explanation of 3rd argument object in apple doc https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html

In all examples like this one How to create a class to send and receive events through NSNotificationCenter in Objective-C? it is nil

Nobody explains it : so why object:nil ?

When is it not nil ?

Community
  • 1
  • 1
user310291
  • 36,946
  • 82
  • 271
  • 487

2 Answers2

7

It is not nil when you are watching a certain object.

Scenario: You have two objects that each fire events through NSNotificationCenter. You only want to receive the events for objectA.

Solution: Subscribe via NSNotificationCenter and pass in objectA as the object parameter.

borrrden
  • 33,256
  • 8
  • 74
  • 109
4

It's not nil when you need to know which object posted notification. Take a look at -(void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender

notificationSender

The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer.

If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.

(from the same NSNotificationCenter reference you linked)

Kreiri
  • 7,840
  • 5
  • 30
  • 36
  • How the observer knows the notificationSender since the Observer design pattern is supposed to decouple observers from observee :) – user310291 May 01 '12 at 09:52
  • @user310291 Is that a real question or a sarcastic comment? – borrrden May 01 '12 at 09:55
  • It is a real question of course: how do I get a reference ? Does it mean I have to create the Observee instance or get it from some controller ? – user310291 May 01 '12 at 10:00
  • @user310291 Yes, usually you register for events from something you create within the same class (for example, MPMoviePlayer). I have the MPMoviePlayer as an iVar, and when I use it, I register the class that contains it for its events (finished, stopped, etc) when the user presses the button that starts the movie, and unregister them when the movie terminates (inside the NSNotification for termination). – borrrden May 01 '12 at 10:02