简体   繁体   中英

Proper way to listen to NSNotifications

Is it proper, if I have 2 notifications on a view controller to have 2 observers like so:

[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifications:) name:@"note1" object:nil];
[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifications:) name:@"note2" object:nil];

Or do I just figure out which notification was run by passing in nil to the name and then checking the notification sent in the handleNotification function:

[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifications:) name:nil object:nil];

Thanks.

Actually, if you pass nil as a name, you'll receive all notifications regardless of their name (not just the two you want). It's better to subscribe to each one separately, by naming them.

Excerpt from Apple documentation:

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

(That point was, at first, not clear to me and I misread it by thinking you would not receive any notification).

You can use the same callback/listener for both, and decide what to do based on the notification received.

You could create a category on NSNotificationCenter to handle the registration of multiple names, that's what categories are made for!

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