Swift - 观察静态成员的变化,而不使用属性观察器。

问题描述 投票:0回答:1

我遇到了下一个情况:从viewDidAppear中,我必须调用特定的函数(将视图控制器换成另一个),当特殊条件应用时(静态成员变为True,另一个类访问这个静态属性,并在某些条件应用时发送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 )

This is changeViewController function:

        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完全陌生。所有的建议都将是非常感激的。

ios swift observer-pattern observers
1个回答
0
投票

你可以通过注册一个通知来使用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)
© www.soinside.com 2019 - 2024. All rights reserved.