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

ach*_*chi 3 xcode nsnotificationcenter ios swift swift3

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

使用方法:

Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)
Run Code Online (Sandbox Code Playgroud)

我有一个单例对象:

class Notifications {

    private static let pipeline = Notifications()
    ...
Run Code Online (Sandbox Code Playgroud)

接收并排队订阅的项目NotificationsPipelineProtocol(它们都是纯快捷方式,此处没有Objective-C NSObject。)

    private func enqueueNotification(_ notification: NotificationsPipelineProtocol) {
        ...
Run Code Online (Sandbox Code Playgroud)

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

        NotificationCenter.default.addObserver(self,
                                       selector: #selector(Notifications.didReceiveNotificationCompletion(_:)),
                                       name: notification.completionNotificationName,
                                       object: notification)
Run Code Online (Sandbox Code Playgroud)

注意 - notification.completionNotificationName是产生Notification.Name项目的计算变量。

但是,当NotificationsPipelineProtocol项目发布到NotificationCenter时:

NotificationCenter.default.post(name: self.completionNotificationName, object: self)
Run Code Online (Sandbox Code Playgroud)

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

    @objc private func didReceiveNotificationCompletion(_ notification : Notification) {
    ...
Run Code Online (Sandbox Code Playgroud)

你知道为什么吗?有没有一种方法可以查看在NotificationCenter中查看特定项目的通知?可能是单例对象掉线了吗?也许#selector的格式不正确?

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

提前致谢。

Pau*_*w11 6

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

NotificationCenter.default.addObserver(self,
                                       selector: #selector(Notifications.didReceiveNotificationCompletion(_:)),
                                       name: notification.completionNotificationName,
                                       object: nil)
Run Code Online (Sandbox Code Playgroud)