Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deinit not called in specific case

I have the following test case: I expect deinit to be called at program termination but it never is. I'm new to Swift but would not think this is expected behaviour. (this is not in a playground)

class Test
{
   init() {
      print( "init" )
   }

   deinit {
      print( "deinit" )
   }
}

print("Starting app")

var test = Test()

print( "Ending App" )

the output is:

Starting app
init
Ending App
Program ended with exit code: 0

If I place the code in a function and then call the function I get expected results

Starting app
init
Ending App
deinit
Program ended with exit code: 0

Shouldn't deinit of the object be called at program termination?

like image 206
Gregor Brandt Avatar asked Jan 28 '23 14:01

Gregor Brandt


2 Answers

I expect deinit to be called at program termination

You should not expect that. Objects that exist at program termination are generally not deallocated. Memory cleanup is left to the operating system (which frees all of the program's memory). This is a long-existing optimization in Cocoa to speed up program termination.

deinit is intended only to release resources (such as freeing memory that is not under ARC). There is no equivalent of a C++ destructor in ObjC or Swift. (C++ and Objective-C++ objects are destroyed during program termination, since this is required by spec.)

like image 175
Rob Napier Avatar answered Jan 31 '23 03:01

Rob Napier


If I place the code in a function and then call the function I get expected results

Yes, this works because the life of the test variable is defined by the scope of the method. When the scope of the method ends (i.e., method gets removed from the Stack), all local variables' life would end unless there are other strong references to those variables.

Shouldn't deinit of the object be called at program termination

There is no way to close an app gracefully in iOS programmatically like Android. The possible ways that an app can be closed are,

  1. By swiping up (terminating) from recent apps list
  2. Or making a deliberate crash.
  3. Or by letting the OS kill your app due to low-memory reasons.

All of your app's memory will be cleared up by the OS when it terminates, so the deinit will not be called, we cannot expect that too. You can note the word termination, which explains the fact that the program didn't end in a proper way, so we can't expect the OS to do the last honors.

like image 26
badhanganesh Avatar answered Jan 31 '23 03:01

badhanganesh