1

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

AlanSTACK
  • 5,525
  • 3
  • 40
  • 99

2 Answers2

3

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).

Sulthan
  • 128,090
  • 22
  • 218
  • 270
1

deinit is an underlying method of Swift classes, not part of UIKit, so not directly related to the view lifecycle, which is:

View Controller Lifecycle (From Apple Documentation)

A deinitializer is called immediately before a class instance is deallocated.

(From The Swift Programming Language)

So generally, in all your example cases, deinit will not get called (unless you specifically remove all strong references to the ViewController on any of those occasions, and even then, only if ARC catches up with it before execution ceases).

Also note that your other example of an unwind segue will not result in a deinit call if you still have a strong reference to the ViewController (usually unintentionally caused by a reference cycle).

Ali Beadle
  • 4,486
  • 3
  • 30
  • 55
  • On a slightly related note. Where do UIKIT callbacks like `viewDidLoad` reside within the application lifecycle? (inactive, active, background)? – AlanSTACK Feb 24 '18 at 22:05