vladakolic vladakolic - 3 months ago 11
Swift Question

My viewcontroller is not being deinitialized after show segue

I have created two view controllers, each with a button that does a show segue to the other view controller.

var counter = 0
class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
counter += 1

print("init viewc \(counter)")
}

deinit {
counter -= 1
print("deinit viewc \(counter)")
}
}


It seems like deinit is never called, each time i return to ViewController, the counter is increasing:

init viewc 1
init viewc 2
init viewc 3


And so on... Am i missing something here? I thought show segue was supposed to release the caller from memory since it is no longer needed. Am i creating new ViewController objects every time I segue now?

Answer

Since you are using a "show" segue, you are creating a new view controller instance each time, effectively presenting the top an ever deeper "stack" of view controllers.

If you want to switch back and forward between single instances of your view controllers then you could use a container view controller, such as a UITabBarController or use a UINavigationController and manipulate the viewControllers property