Memory Management in Swift: ARC

Orhan Aykut Kardeş
3 min readMar 24, 2023

--

The deallocation of an object, whether it’s a class, structure, or enumeration is critical to ensure optimal performance and efficiency of the system by freeing up the memory occupied by the object when it is no longer needed. Properties, constants, and variables can maintain a reference to same class instance since class instances are passed by reference.

ARC is based on a simple idea of monitoring class instances and determining the appropriate time to deallocate them by counting their references.

Let’s explain this with an example.

This defines a class Client which has print statements to show when you have initialized or deallocated it.

The console log confirm that the Client object was initialized and the fact that the deinit method’s print statement was not executed that the object was not deallocated, because it has not yet gone out of scope. So, created object is never removed from memory.

Enclosing the client instance within a method will enable it to go out of scope, allowing ARC to deallocate the object.

The scope of the client instance is established by the registerClient() function. Once this scope is exited, the Client object is expected to be deallocated.

The initialization and deallocation print statements both appear. These statements show that you’ve deallocated the object at the end of the scope.

In registerClient(), first, a Client object is created, then its reference is copied, and finally, its destination is updated.

In order to automatically manage the memory of the Client object, the Swift compiler inserts:

  • a retain operation when a reference begins.
  • a release operation after the last use of the reference.

Let’s take a look at the code and see what happens when it runs:

  • Client object is created on the heap and given a reference count of 1.
  • retain operation (added by the compiler) executes in preparation for the new client2 reference, increasing the reference count to 2.
  • release operation is executed after the last use of the client1 reference, decrementing the reference count to 1.
  • After the last use of reference client2 , a release operation is performed and the reference count is decremented to 0.

But Reference checking needs your assistance.

In order to prevent memory leaks and retain cycles, Automatic Reference Counting (ARC) requires some assistance from you. In the upcoming series, we will focus specifically on retain cycles.

--

--