0

I've found a memory leak in an app where the following is done:

Imagine two view controllers, each of which calls a function in the appDelegate similar to this:

func switchRootViewController() {    
    let vc = getTheOtherViewController()
    self.window?.rootViewController = vc
}

So far this is working well - the other VC is shown and the one that called the function is deallocated.

But when you present a third view controller from first or second VC via: present(ThirdViewController(), animated: true)

And then call the above function in the appDelegate from ThirdVC (to show viewController one or two by making it the rootViewController), this ThirdVC and the VC that presented it do not get deallocated.

Any idea why that is?

Can post sample project if needed. VC's are instantiated from storyboard if that makes any difference.

4

1 回答 1

1

你在这里搞乱了视图层次结构。rootViewController在切换到新视图控制器之前,您应该关闭当前所有显示的视图控制器。这是我发现的唯一可行的解​​决方案!

您的switchRootViewController方法应该如下所示,

func switchRootViewController() {    
   if var topController = UIApplication.shared.keyWindow?.rootViewController {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
        topController.dismiss(animated: true, completion: {
            let vc = getTheOtherViewController()
            self.window?.rootViewController = vc
        })
    }
}

如果您有多个视图控制器,

func switchRootViewController() {   
   self.view.window!.rootViewController?.dismiss(animated: true, completion: {
      let vc = getTheOtherViewController()
      self.window?.rootViewController = vc
   })    
}
于 2017-12-13T08:12:30.790 回答