Deinitialization

When an object’s reference count reaches zero, Swift removes the object from memory and marks that memory as free.

A deinitializer is a special method on classes in Swift that runs when an object’s reference count reaches zero, but before Swift removes the object from memory.

Take a look:

class Person {

//…

deinit {

print("(firstName) (lastName) is being removed from memory!")

}

}

Much like init is a special method in class initialization, deinit is a special method that handles deinitialization. Unlike init, deinit isn’t required and is automatically invoked by Swift. You also aren’t required to override it or call super within it. Swift will make sure to call each class deinitializer.

If you add this deinitializer, you’ll see the message Johnny Appleseed is being removed from memory! in the debug area after running the previous example.

What you do in an deinitializer is up to you. Often you’ll use it to clean up other resources, save state to a disk or execute any other logic you might want when an object goes out of scope.

results matching ""

    No results matching ""