iOS 解決設定rootViewController 記憶體不釋放問題

HimmaHorde發表於2020-02-06

keyWindow 設定新的 rootViewController時如果之前有模態的檢視控制器,那麼需要呼叫dismiss方法,並在complete回撥中設定rootViewController

self.dismiss(animated: false) {
    UIApplication.shared.keyWindow?.rootViewController = NewViewController()
}
複製程式碼

模態了很多層怎麼辦?

下面提供一個快捷查詢所有模態控制器的方法

    func safeSet(keyWindow rootViewController: UIViewController) {
        var tempArr = [UIViewController]()
        var tempVc = UIApplication.shared.keyWindow?.rootViewController?.presentedViewController
        var flag =  tempVc != nil
        
        while flag {
            tempArr.append(tempVc!)
            tempVc = tempVc?.presentedViewController
            flag = tempVc != nil
        }
        for (index, item) in tempArr.reversed().enumerated() {
            if index == tempArr.count - 1 {
                item.dismiss(animated: false) {
                    UIApplication.shared.keyWindow?.rootViewController = rootViewController
                }
            } else {
                item.dismiss(animated: false, completion: nil)
            }
        }
    }
複製程式碼

iOS13 蘋果修復了這個問題

是的如果你只支援 iOS13 那麼請忽略上面的那個問題。 給我們的程式碼加上版本判斷

    func safeSet(keyWindow rootViewController: UIViewController) {
        if #available(iOS 13.0, *) {
            UIApplication.shared.windows.first?.rootViewController = rootViewController
        } else {
            var tempArr = [UIViewController]()
            var tempVc = UIApplication.shared.keyWindow?.rootViewController?.presentedViewController
            var flag =  tempVc != nil
            
            while flag {
                tempArr.append(tempVc!)
                tempVc = tempVc?.presentedViewController
                flag = tempVc != nil
            }
            for (index, item) in tempArr.reversed().enumerated() {
                if index == tempArr.count - 1 {
                    item.dismiss(animated: false) {
                        UIApplication.shared.keyWindow?.rootViewController = rootViewController
                    }
                } else {
                    item.dismiss(animated: false, completion: nil)
                }
            }
        }

    }
複製程式碼

相關文章