Search code examples
swiftuiviewcontrollerpresentviewcontrollerdeinit

Deinitialize presented view controller


I have the next function

func switchRootViewController(rootViewController: UIViewController) {
    let window = UIApplication.shared.windows.first!
    window.rootViewController = rootViewController
    window.makeKeyAndVisible()
}

And I use it in a presented view controller, ex in PresentedViewController.

let navigationViewController = UINavigationController(rootViewController: PresentedViewController())
present(navigationViewController, animated: true, completion: nil)

But when I switch to the needed view controller, my presented view controller doesn't deinitialize. I have to use this way, first dismiss:

self.dismiss(animated: true, completion: {
    switchRootViewController(rootViewController: HomeViewController.instantiate())
}) 

instead of simple

switchRootViewController(rootViewController: HomeViewController.instantiate())

Solution

  • UIViewController objects are retained when presented by another UIViewController. To release your view controllers, they need to be removed from the view hierarchy, which you can accomplish by dismissing them. As far as where to dismiss your view controller, I'm not sure because you haven't given enough information. But you need to dismiss any view controller that you want released from memory.