有人能解释一下推送通知代码中的对象部分吗?



我遇到一段代码,它注册了一个通知:

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

然后用:

触发它
[[NSNotificationCenter defaultCenter] postNotificationName:@"someStuff" object:self];

为什么一个对象被设置为nil而另一个对象被设置为self?这是做什么的?

首先考虑第二种情况,当您发布通知时,您要指出哪个对象是该通知的发送者。通常是"self",但你也可以以其他对象的名义发布通知。

另一方面,当你注册观察通知时,你可以指定你只想观察由特定对象发布的通知。所以你可以说"我想要观察‘酷的新数据’通知,但是只有当这个特定对象发布了时,才能观察"。如果其他对象说有"很酷的新数据",我就不感兴趣了。"

如果你在注册观察者时传递nil作为'object'参数,那么你说你不在乎谁发布了这个通知,你希望你的选择器(或块)为任何发送者触发。因此,如果任何人发布'酷的新数据',我想知道它。

顺便说一句,这些不是"推送通知"。这是一个不同的功能/API

引用apple docs..第一个对象是

notificationSender

The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the

观察者。

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

第二个是

notificationSender

The object posting the notification.

那么在第二种情况下,这个告诉谁实际上是发送这个通知的,那就是那个类本身。

最新更新