ios - 明确 NSNotification 的 addObserver 函数中 notificationSender 的用途

标签 ios swift avfoundation avplayer nsnotificationcenter

有人可以解释一下 NSNotificationaddObserver 函数中 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.notificationkMyAppNotification 正是出于这个原因。

至于您链接的特定代码行,我实际上不知道实现细节,但我假设您是否添加了一个监听器,其 notificationSender 属性指向一个对象,您还需要使用 notificationSender 属性集删除相同的监听器,否则不删除观察者可能会导致内存泄漏。但我必须再次阅读文档才能弄清楚这一点。

关于ios - 明确 NSNotification 的 addObserver 函数中 notificationSender 的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34805955/

相关文章:

javascript - 我应该用哪种方法注入(inject)javascript? (stringByEvaluatingJavaScriptFromString)

ios - MKMapview 中 poi 点的详细信息

ios - 在 iOS 上使用 HEVC 编码器输出巨大的视频

ios - swift : SKStoreReviewController - how often can it be called?

ios - 蓝牙标志在 iPhone 上是否可以用作字符?

swift - 将数据从flutter传递到原生IOS

swift - self.addChild 是做什么的?

swift - 可选类型 'NSNumber' 的值未解包;您的意思是使用 '!' 还是 '?' ?

ios - 如何在转换为视频时为图像制作动画

ios - CMSampleBuffer 的样本呈现时间代表什么?