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?
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.)
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,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With