2017-04-15 81 views
1

似乎Swift 3中围绕NotificationCenter发生了一些变化,我似乎无法完全理解它。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(他们都是纯粹的迅速,没有Objective-C的NSObjects在这里。)

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

在其中增加了自己作为一个观察者的通知中心

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

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

但当NotificationsPipelineProtocol项目职位的通知中心:

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

观察员不调用它的订阅相关的方法:

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

你可能知道为什么吗?有没有办法在NotificationCenter中查看特定项目订阅的通知?也许单身物体放弃它的观察?也许#选择器格式不正确?

XCode不给我任何警告或错误。

在此先感谢。

+0

凡'enqueueNotification'叫什么名字? 'enqueueNotification'中的'notification'是发布你想要观察的所有通知的对象吗?你是否希望'object'参数为'nil'? – Paulw11

+0

我构建了一个'管道'又名一个通知队列,它在那里建立并确认处于管道中。我会尝试不包含对象的引用 – achi

+0

它工作!我不知道为什么,可能你知道吗?另外,如果你发布这个答案,我会接受它:) – achi

回答

3

您传递NotificationPipelinesProtocol对象addObserver。这意味着您只会收到该对象发布的通知。如果你想获得张贴任何对象的指定名称的通知那么你应该通过nil

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

这使我与'addObserver(forName:object:queue:using:)'变种绊倒了,因为我忘记了'using'块自动捕获观察员。 – clozach