有人可以解释一下 NSNotification
的 addObserver
函数中 notificationSender
的用途吗?
这是 Apple 文档的解释:
notificationSender
The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer.
If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.
我们使用通知在视频结束时做出响应。代码:
NSNotificationCenter.defaultCenter().removeObserver(self, name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)
其中 playerItem
包含相关视频。然而,为 object
传递 nil
似乎没有明显的效果。
我们最好使用 nil
而不是 playerItem
,因为我们不需要创建另一个类变量。
使用nil
有什么风险,使用playerItem
有什么优势?
最佳答案
指定 notificationSender
的唯一原因是您是否选择了其他对象(您不想收听的对象)将发送给您的通知名称。指定 notificationSender
类似于委托(delegate)关系,将其保留为 nil 意味着绝对任何对象都可以向您发送具有相同字符串的通知,并且您将处理它。
实际上,只要您选择唯一的通知字符串,这很少会成为问题。您会看到人们使用 com.my.app.name.notification
或 kMyAppNotification
正是出于这个原因。
至于您链接的特定代码行,我实际上不知道实现细节,但我假设您是否添加了一个监听器,其 notificationSender
属性指向一个对象,您还需要使用 notificationSender
属性集删除相同的监听器,否则不删除观察者可能会导致内存泄漏。但我必须再次阅读文档才能弄清楚这一点。
关于ios - 明确 NSNotification 的 addObserver 函数中 notificationSender 的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34805955/