Retain Cycles and Memory Management in Swift

All Aboard and Manage!

Steven Curtis
6 min readMar 29, 2022

--

Photo by SpaceX on Unsplash

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE)

Video link:

  • Here is similar material presented in a video format

Terminology

Retain cycles: This is the state when two objects hold weak references to one another. Since the first object’s reference count cannot be 0 until the second object is released, and the second object’s reference count cannot be 0 until the first objet is released neither object can be released! It is self-evident that it is not possible to create retain cycles with value types, as they are passed by value.

Memory footprint: the amount of memory that a program uses or references. The more resources that are used, the larger the footprint. If objects are not released the occupied memory will grow, leading to memory warning and crashes.

Memory leak: A memory leak is a portion of memory that will never be used, yet is held onto forever. It is both a waste of space and can cause including crashes for the end-user.

Avoiding Retain cycles

Understanding ARC

Swift uses Automatic Reference Counting (ARC) to manage memory in an App. This means that Swift automatically releases memory which is no longer used in the App — this is rather fantastic and means that we can deliver a great user experience!

ARC only applies to reference types (that is, classes) and in this article the terms classes and objects are used for the instances that need to be managed in this way.

When an object is created, it’s reference count will be set at 1. Each time a strong reference is made to the object this count will be incremented by one. Each time an object is released (deallocated) the count will be decremented by 1. When an object’s reference count reaches zero, it will be…

--

--