When to Use Strong References Over Weak References in Swift
Retain Cycle

Before we start, let’s understand what the retain cycle is and how memory leaks happen.

Let’s study the retain cycle with an example:

We created objects of both the class, First and Second , and made them hold each other’s reference, hence increasing the reference count to 2 each.

When we try to deallocate memory, deinit was not called because not all the references were removed. Can we release it now? Well no, because they’re inaccessible, causing a memory leak.

So the memory leak is of the inaccessible memory, which happened when we were unable to deallocate the object.

We solve this by manually handling the deallocation:

/// 1. By manual handling object1?.secondOne = nil

object2?.firstOne = nil object2 = nil

object1 = nil

And making one of the properties weak :

weak var firstOne: First? // changing line 12 ///// 2. By Weak approach object2 = nil

object1 = nil

Great — we know how to avoid the retain cycle, but sometimes we misinterpret whether it is actually happening.
['Arjun Baru']
['iOS', 'Xcode', 'Swift', 'Programming', 'Mobile']