首页 > 解决方案 > 为什么我无法在 SwiftUI 中的 View 结构内收到有关观察者类的通知?

问题描述

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

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)")
    }
}

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

标签: swiftswiftuinsnotificationcenter

解决方案


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

这是固定的变体。使用 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)

推荐阅读