簡體   English   中英

Swift - 觀察 static 成員變化,不使用屬性觀察者

[英]Swift - observe static member change, without using property observer

I've got next situation: from the viewDidAppear I have to call the specific function ( to change the view controller to another one) when the special condition applied ( static member changes to True, another class access this static property and send True once the某些條件適用)

如果我對屬性觀察者這樣做:

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

嘗試呈現視圖不在 window 層次結構中的視圖控制器時會拋出錯誤

並且,它在 LoadViewController class 內部執行

據我了解,避免此錯誤的唯一方法是從viewDidApper調用 function ,它不能在這種情況下使用,因為我必須僅在應用條件時調用它。 是否有任何替代方法可以使用屬性觀察器執行該操作?

我確信有多種方法可以執行此操作,並且我這邊可能存在誤解。 我是一名非常新的開發人員,對 Swift 完全陌生。 所有的建議將不勝感激。

您可以通過注冊通知來使用 NotifiationCenter,然后在您想要更新某些內容時調用它,例如聊天應用程序中的“updateConversations”。 例如在 viewDidLoad() 中,注冊你的通知:

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

將此 function 添加到 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM