Understanding the class lifecycle

In the previous chapter, you learned that objects are created in memory and that they’re stored on the heap. Objects on the heap are not automatically destroyed, because the heap is simply a giant pool of memory. Without the utility of the call stack, there’s no automatic way for a process to know that a piece of memory will no longer be in use.

In Swift, the mechanism for deciding when to clean up unused objects on the heap is known as reference counting. In short, each object has a reference count that’s incremented for constant or variable with a reference to that object, and decremented each time a reference is removed.

Note: You might see the reference count called a “retain count” in other books and online resources. They refer to the same thing!

When a reference count reaches zero, that means the object is now abandoned

since nothing in the system holds a reference to it. When that happens, Swift will clean up the object.

Here’s a demonstration of how the reference count changes for an object. Note that there’s only one actual object created in this example; the one object just has many references to it.

var someone = Person(firstName: "Johnny", lastName: "Appleseed")

// Person object has a reference count of 1 (someone variable)

var anotherSomeone: Person? = someone

// Reference count 2 (someone, anotherSomeone)

var lotsOfPeople = [someone, someone, anotherSomeone, someone]

// Reference count 6 (someone, anotherSomeone, 4 references in lotsOfPeople)

anotherSomeone = nil

// Reference count 5 (someone, 4 references in lotsOfPeople)

lotsOfPeople = []

// Reference count 1 (someone)

someone = Person(firstName: "Johnny", lastName: "Appleseed")

// Reference count 0 for the original Person object!

// Variable someone now references a new object

In this example, you don’t have to do any work yourself to increase or decrease the object’s reference count. That’s because Swift has a feature known as automatic reference counting or ARC.

While some older languages require you to increment and decrement reference counts in your code, the Swift compiler adds these calls automatically at compile time.

Note: If you use a low-level language like C, you’re required to manually free memory you’re no longer using yourself. Higher-level languages like Java and C# use something called garbage collection. In that case, the runtime of the language will search your process for references to objects, before cleaning up those that are no longer in use. Garbage collection, while more powerful than ARC, comes with a performance cost that Apple decided wasn’t acceptable for mobile devices or a general systems language.

results matching ""

    No results matching ""