Swift NotificationObserver 无法使用模态呈现 ViewController

Swift NotificationObserver not working with a modally presented ViewController

我目前正在尝试在按下按钮时打开一个模态呈现的 ViewController,并通过通知向这个模态 ViewController 发送一些数据。问题是 NotificationObserver 似乎无法处理模态呈现的 ViewController.

我是这样推送通知的:

let scores = ["Bob": 5, "Alice": 3, "Arthur": 42]
        
NotificationCenter.default.post(Notification(name: .didReceiveData, object: self, userInfo: scores))

这是我添加观察者的方式

NotificationCenter.default.addObserver(self, selector: #selector(self.onDidReceiveData(_:)), name: .didReceiveData, object: nil)

@objc func onDidReceiveData(_ notification:Notification) {
    if let data = notification.userInfo as? [String: Int]
        {
            for (name, score) in data
            {
                print("\(name) scored \(score) points!")
            }
        }
}

我已经尝试在 viewDidLoad 和 viewWillAppear 中添加 NotificationObserver,但这两个选项都不适合我。

有人有解决此类问题的方法吗?

(我正在使用 Xcode 12.1,并将其部署在 IOS 14.1 上)

首先确保您先订阅,并且仅在发送通知后订阅。尝试设置几个断点并检查您的订阅/post 流程是否正确。

此外,对于我来说,更准确的数据传递方式是使用 viewController 的属性。

感谢安德鲁的回答,我刚刚通过拒绝使用通知解决了这个问题。

在 StoryboardSegues 的准备函数中,我为 ViewController 创建了一个实例,我将用户发送到并在其他 ViewControllers class 中操作了一个变量这个实例。

let destinationViewController = segue.destination as! OtherViewController

destinationViewController.variable = someContent