NSNotification object

我们正常使用NSNotification进行消息传递的时候,附带参数都是通过userInfo来实现。但是最近试了一下,例如我想传个BOOL类型的参数,试着用object来传递也是可以实现的。试了以下几种情况:

  • post填nil, add填XXX。此时收不到通知。
  • post填XXX, add填nil。此时收到通知。
  • post填XXX, add填XXX。此时收到通知。
  • post填nil, add填nil。此时收到通知。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(XXXX:) name:@"XXXXX" object:objectA];
[[NSNotificationCenter defaultCenter] postNotificationName:@"XXXXX" object:objectA userInfo:@{@"key":@"param"}];

可是按道理object这个参数并不是用来做参数传递的。翻了一下官方文档:官方解释最后一个参数为notificationSender,解释如下:

The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer. When nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.

官方并没有对object参数做限制,但是正确使用NSNotification的姿势应该是所有想进行传递的参数都应该放在userInfo中,object只作为收发通知的一个限制要求。

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.