【问题标题】:Why I can't receive a notification on an observer class inside a View struct in SwiftUI?为什么我无法在 SwiftUI 中的 View 结构内收到有关观察者类的通知?
【发布时间】:2020-11-07 14:09:46
【问题描述】:

我有以下代码,我在其中创建了一个充当默认通知观察者的类。但是通知永远不会到达:

struct NotificationCenterExampleView: View {
    
    let observerA = ObserverClassA()
    
    init() {
        print("NotificationCenterExampleView init")
        
        
        NotificationCenter.default.addObserver(observerA, selector: #selector(ObserverClassA.receivedNotification(notification:)), name: Notification.Name("CustomNotification"), object: "This is the message")
        let notificationToPost = Notification(name: Notification.Name("CustomNotification"), object: "Message being sent", userInfo: nil)
        NotificationCenter.default.post(notificationToPost)
    }
    
    var body: some View {
        Text("Notification Center Example")
            .frame(minWidth: 250, maxWidth: 500, minHeight: 250, maxHeight: 500)
    }
}

class ObserverClassA: NSObject {
    
    @objc func receivedNotification(notification: Notification) {
        let message = notification.object as! String
        print("Message received: \(message)")
    }
}

我知道使用 .publisheronReceive 这将在 View 结构中工作,但是这段代码不起作用的实际原因是什么?

【问题讨论】:

    标签: swift swiftui nsnotificationcenter


    【解决方案1】:

    通知由对象匹配,因此如果您通过一个对象订阅但用另一个对象发布,则不会触发订阅者。

    这是固定的变体。使用 Xcode 12.1 测试。

        NotificationCenter.default.addObserver(observerA, 
           selector: #selector(ObserverClassA.receivedNotification(notification:)), 
           name: Notification.Name("CustomNotification"), 
           object: nil)   // << subscribe for all
    
        let notificationToPost = Notification(name: Notification.Name("CustomNotification"), object: "This is the message", userInfo: nil)
        NotificationCenter.default.post(notificationToPost)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 2020-02-23
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      相关资源
      最近更新 更多