Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is parameter `object` in NSNotification addObserver:?

One of my class named Message.m is posting a notification with an object sentObject as below

NSDictionary *sentObject = [NSDictionary dictionaryWithObjectsAndKeys:draftData.arr,@"data", nil];

//Post notification to inform a receiver to reload data     
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadDuringSave" object:self userInfo:sentObject];

DraftData.m will be be the receiver to catch the notification as follow

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(dataReloaded:) 
                                             name:@"reloadDuringSave" 
                                           object:nil];

For posting notification, userInfo can be nil or can be an object (like sentObject as type of NSDictionary in this example).

Question:

What are other params for object in addObserver method? Can they be anything other than nil, and if so what?

like image 900
tranvutuan Avatar asked Jul 25 '12 06:07

tranvutuan


People also ask

What is addObserver in Swift?

addObserver(forName:object:queue:using:) Adds an entry to the notification center to receive notifications that passed to the provided block.

What is NotificationCenter default addObserver?

default — This is the notification variable you can create it globally inside your class if you having more notifications. addObserver(self, — This is for the class where we are going to observer notification.


3 Answers

That "object" parameter to "addObserver" is an optional filter. Upon posting a notification you can set an object to the sender of the notification, and will then only be notified of that sender's events. If set to "nil" you will get all notification of this type (regardless who sent them).

like image 86
Thilo Avatar answered Oct 08 '22 15:10

Thilo


You can use it to pass any object with the notification. The receiver of the notification will then be able to access that object. For example, you could implement dataReloaded like this:

- (void)dataReloaded:(NSNotification *)notification {

    NSLog(@"%@", notification.object); // this will log the object you passed in addObserver:selector:name:object:

}

It can be useful when you want to pass on data with your notification, so that the receiver of a notification can use that data too.

like image 35
Scott Berrevoets Avatar answered Oct 08 '22 15:10

Scott Berrevoets


For anyone interested in apple's documentation. This is what it says:

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.

like image 4
nomann Avatar answered Oct 08 '22 15:10

nomann