简体   繁体   中英

NSNotification send multiple objects?

I am learning how to use NSNotificationCenter. My understanding is that for each notification, you can send a single object. Is there a way to send a notification with multiple objects or must I post a new notification for each object?

You can pass any information you like in the userInfo argument of postNotification:object:userInfo: .

For example, you could call the method as follows:

NSDictionary *accountDetails = @{@"accountHolder":@"Mr John Smith",
                                 @"accountNumber":@(01234567),
                                 @"sortCode":@"01-98-34"};

[[NSNotificationCenter defaultCenter] postNotificationName:@"BankDidCreateNewAccount" object:self userInfo:accountDetails];

Just to explain in more detail: to post notifications with an object, you'd use either

-postNotificationName:object: or -postNotificationName:object:userInfo:

In the object argument, you may only supply a single object. Typically, the object argument is the notificationSender , ie you would pass self from wherever you post the notification.

If you have registered for notifications using -addObserver:selector:name:object: , and you passed any value but nil for the object argument, then you will only receive notifications where the posted notification object ( object argument in -postNotificationName:object: ) matches the the object argument in -addObserver: .

If you pass nil in -addObserver: then the object value of -postNotification: is ignored for this particular observer.

Wow, that sounds complicated. But it's actually very simple. object argument must match if used in -addObserver: .

Use userInfo argument to supply more details to the notification observer.

A notification can only have one object . For multiple objects it depends what you want to send them for. If each is being observed separately then yes, you need to send multiple notifications. If you just need to send context info then you should use userInfo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM