gpt4 book ai didi

ios - Swift 3,NotificationCenter 观察者缺少发布的通知

转载 作者:搜寻专家 更新时间:2023-10-31 22:11:39 24 4
gpt4 key购买 nike

Swift 3 中的 NotificationCenter 似乎有一些变化,我似乎不太正确。

使用:

Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)

我有一个单例对象:

class Notifications {

private static let pipeline = Notifications()
...

接收订阅 NotificationsPipelineProtocol 的项目并将其排入队列。 (它们都是纯 swift,这里没有 Objective-C NSObject。)

    private func enqueueNotification(_ notification: NotificationsPipelineProtocol) {
...

在其中它将自己添加为 NotificationCenter 的观察者

        NotificationCenter.default.addObserver(self,
selector: #selector(Notifications.didReceiveNotificationCompletion(_:)),
name: notification.completionNotificationName,
object: notification)

注意 - notification.completionNotificationName 是一个生成Notification.Name 项的计算变量。

但是当 NotificationsPipelineProtocol 项发送到 NotificationCenter 时:

NotificationCenter.default.post(name: self.completionNotificationName, object: self)

观察者不调用它关联的订阅方法:

    @objc private func didReceiveNotificationCompletion(_ notification : Notification) {
...

你知道为什么吗?有没有办法在 NotificationCenter 中查看特定项目订阅了哪些通知?也许单例对象放弃了它的观察?也许 #selector 的格式不正确?

XCode 没有给我任何警告或错误。

提前致谢。

最佳答案

您正在将 NotificationPipelinesProtocol 对象传递给 addObserver。这意味着您只会收到该对象发布的通知。如果你想接收由任何对象发布的指定名称的通知,那么你应该传递nil:

NotificationCenter.default.addObserver(self,
selector: #selector(Notifications.didReceiveNotificationCompletion(_:)),
name: notification.completionNotificationName,
object: nil)

关于ios - Swift 3,NotificationCenter 观察者缺少发布的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43431431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com