iosswiftios-lifecycle

When do ViewControllers call deinit? During move to background? During move to suspended?


I know that a ViewController will have its deinit method called once it is no longer needed (e.g. after an unwind segue and subsequent dismissal).

But I was wondering what the behavior of deinit was in the context of the application lifecycle.

My questions

1) When (which app state active/inactive/background/etc), if at all, does deinit get called if the app is terminated by the system due to memory constraints

2) When (which app state active/inactive/background/etc), if at all, does deinit get called if the app is terminated by the user through the recently used app screen

3) When (which app state active/inactive/background/etc), if at all, does deinit get called if the app is moved to the background by the user accepting an incoming call

4) When (which app state active/inactive/background/etc), if at all, does deinit get called if the app is moved to the background by the user opening a different app


Solution

  • When the app is is terminated abruptly (your cases 1 or 2), usually no code is called, including any deinit code. There is no need for deinit becasue all application memory is deallocated at once.

    Otherwise, deinit is called when an object is no longer needed and this has nothing to do with external events, whether the app is in the foreground or in the background. It depends only when you, as a programmer, release the ownership of the object (e.g. when you pop a navigation controller or dismiss a presented controller).