2017-04-15 51 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