Search code examples
iosswiftuiviewcontrollerdeinit

Will deinit gets called when a view controller gets disappeared?


I created two view controllers like

Navigation controller -> View Controller -> Details View Controller
          1                     2                      3

The (2) View Controller has a button in it which when clicked will shows (3) Details View Controller. I have created a segue from button to (3) VC.

I have added deinit blocks in those two classes.

deinit {
    print("vc deinit")
}

However, this does not get logged. When will a view controller get deallocated?

Sample code


Solution

  • In this case, the only deinit will get called is the second one (the one implemented in the Details View Controller) each time you tap the back button on the navigation (pop to the previous view controller).

    So, why the first deinit (the one in the View Controller) didn't get called?

    That's because it is the first view controller in the navigation controller stack. Pushing to the second view controller does not mean that the previous one(s) one has been deallocated and still exists as the first element in the navigation stack; As an example, that's why viewDidLoad method should not get called when you come back from a popped view controller, which means it did not get deallocated.