Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Manual Memory Management with deinit
Written by Team Kodeco

In Swift, Automatic Reference Counting (ARC) automatically manages the memory of your objects, but sometimes you may need to manually manage the memory of your objects. One way to do this is by using the deinit method.

The deinit method is called just before an instance of a class is deallocated. This is the perfect place to release any resources that were acquired by the object during its lifetime, such as file handles, network connections, or other resources that need to be closed.

Here’s an example of a simple class, MyClass, that uses the deinit method to release a resource:

import Foundation

class MyClass {
  var fileHandle: FileHandle?

  init() {
    // open a file handle
    let file = URL(fileURLWithPath: "file.txt")
    fileHandle = try? FileHandle(forWritingTo: file)
  }

  deinit {
    // close the file handle
    fileHandle?.closeFile()
  }
}

In this example, the MyClass class opens a file handle when it is initialized and closes the file handle when it is deallocated.

It’s important to note that the deinit method is called automatically by the Swift runtime and you should never call it yourself. You also should never store any strong reference inside the deinit method otherwise it’ll cause memory leak.

© 2024 Kodeco Inc.