[英]Swift 3, NotificationCenter observer missing posted Notification
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 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.