首页 > 解决方案 > Swift - 观察静态成员的变化,而不使用属性观察器

问题描述

我遇到了下一个情况:当应用特殊条件时(静态成员更改为 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)
        }

它会抛出一个错误尝试呈现视图不在窗口层次结构中的视图控制器

而且,它在 LoadViewController 类中执行

据我了解,避免此错误的唯一方法是从viewDidApper调用该函数,该函数不能在这种情况下使用,因为我必须仅在应用条件时调用它。是否有任何替代方法可以使用属性观察器执行该操作?

我确信有多种方法可以执行此操作,并且我这边可能存在误解。我是一个非常新的开发人员,对 Swift 完全陌生。所有的建议将不胜感激。

标签: iosswiftobserver-patternobservers

解决方案


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

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

将此函数添加到类中:

@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)

推荐阅读