Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Automatic Reference Counting
Written by Team Kodeco

Automatic Reference Counting (ARC) is a memory management mechanism used in Swift to automatically manage the memory of objects.

ARC works by keeping track of the number of references to an object and automatically release it when there are no more references to it.

This way, objects that are no longer needed are automatically deallocated and objects that are still needed aren’t deallocated.

You don’t have to do anything special to use ARC - it works for you behind the scenes. Here is an example that shows you a bit about how it works:

class MyClass {
  var name: String
  init(name: String) {
    self.name = name
  }
  deinit {
    print("MyClass \(name) is being deinitialized")
  }
}

var myObject: MyClass? = MyClass(name: "object1")
myObject = nil
// Output: MyClass object1 is being deinitialized

In this example, you created an instance of the MyClass class and assign it to myObject. Then, you set it to nil, which releases the reference to the object and triggers its deinitialization.

When an object is deinitialized, it calls the deinitializer on an object (deinit). In this example, MyClass overwrites the deinitializer and prints out a message when it’s called, to help you better understand when ARC automatically deallocates the object (i.e. once there are no longer any references to the object).

© 2024 Kodeco Inc.