Search code examples
iosswiftseguedismisspresentviewcontroller

How to avoid memory leaks while presenting / segueing to new View Controllers


In my app I have a MainViewController where user can add, remove and reorder items in CollectionView. Each Collection View Cell initiates segue to a new VC (n-th VC in the image below). From the newly presented vc user can go back to the MainVC or segue to the next (or previous) VC that's also accessible from the MainVCs Collection View.

Since the order of items in Collection View is dynamic I'll have instantiate the next VC and then present it:

let nextVC = storyboard?.instantiateViewController(withIdentifier: "NextVC")
present(nextVC!, animated: true, completion: nil)

MainVC VC presented by the MainVC

My question is (are):

Do I have to worry about a memory leaks if I use unwind segue when the user taps on goBackToMainVC (I.e. will all previously instantiated VCs be automatically dismissed?)

If the user decides not to go back to the MainVC, should I dismiss the current VC before presenting a new one? If so, where should I call the dismiss function?


Edit: Additional question: Would adding

if (presentingViewController?.restorationIdentifier != "MainVC") {
            presentingViewController?.dismiss(animated: false, completion: nil)
        }

to every VC accessible from the collection view in MainVC solve my problem?


Solution

  • If you are dismissing or unwinding back to the main controller, it would deallocate the loaded view controller(s) that was loaded when presenting. That is, providing there are no strong references to anything to those view controllers.

    To verify the view controllers are being deallocated, you can print something to the console when the controllers are dismissed via deinit.

    deinit {
        print("deinit called")
    }