简体   繁体   中英

Why set sender to nil when sending NSNotification

I see a lot of people, including textbooks, sending notification as

[[NSNotificationCenter defaultCenter] postNotificationName:@"someNotification" object:nil userInfo:data];

Why would they prefer that form instead of the following?

[[NSNotificationCenter defaultCenter] postNotificationName:@"someNotification" object:self userInfo:data];

Does specifying the sender affect the receiver in some negative way? I imagine specifying the sender would be best practice.

When you set the sender to nil , it implies you are posting a "general" notification, and that can be representative for all the objects that post this notification. Think of it from the subscriber end; when you request notifications from a certain object, it scopes it to only those posted by that object. If you set object to nil while subscribing, you'll receive all the someNotification s regardless of object.

You can pass any object as the object of a notification, but the convention is that the object is the "thing that is doing the notifying". If you pass nil to object then it is not going to harm anything but obeserver will not identifying the current object. Self is required when you are posting multiple notification, in that case observer need to know the current object.

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