Swift - 观察静态成员变化,不使用 属性 观察者

Swift - observe static member change, without using property observer

我有下一种情况:当应用特殊条件(静态成员变为 True,另一个 class访问此静态 属性 并在满足特定条件后发送 True)

如果我用 属性 观察者这样做:

//this is property of load view controller
  static var isFilled: Bool = false {
        didSet{
            if isFilled == true {
            print("data is Filled")
                //load view controller - my present VC, which I want to switch
                var loadVC = LoadViewController()
             loadVC.changeViewController(vc: loadVC )

这是 changeViewController 函数:

        func changeViewController(vc: UIViewController) {
            let sb = UIStoryboard(name: "Main", bundle: nil )

            //main view controller - controller, which i want to Go to

            var mainViewController = sb.instantiateViewController(withIdentifier: "ViewController") as! ViewController
            vc.present(mainViewController, animated: true, completion: nil)
        }

它会抛出一个错误attempt to present viewcontroller who view is not in the window hierarchy

而且,它是在 LoadViewController 内部执行的 class

据我所知,避免此错误的唯一方法是从 viewDidApper 调用函数,在这种情况下不能使用,因为我必须调用仅当条件适用时。 是否有任何替代方法可以使用 属性 观察者来执行 w/o?

我敢肯定有多种方法可以执行此操作,而且我这边可能存在误解。我是新手开发者,对 Swift 完全陌生。非常感谢所有建议。

您可以通过注册通知来使用 NotifiationCenter,然后在您想要更新某些内容时调用它,例如 "updateConversations" 在聊天应用程序中。例如在 viewDidLoad() 中,注册你的通知:

NotificationCenter.default.addObserver(self, selector: #selector(self.updateConversations(notification:)), name: NSNotification.Name(rawValue: "updateConversations"), object: nil)

将此函数添加到 class:

@objc func updateConversations(notification: NSNotification) {
    if let id = notification.userInfo?["id"] as? Int,
        let message = notification.userInfo?["message"] as? String {
        // do stuff
    }
}

在您应用的任何位置使用通知:

let info = ["id" : 1234, "message" : "I almost went outside today."]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateConversationsList"), object: self, userInfo: info)