Delegate Retain Cycle in Swift
Why delegate should be weak var?
Before you begin I highly recommend you to check ARC story.
We will design protocol and classes in order to show retain cycle on delegates.
With using lazy keyword we are not initializing delegate which means there is no memory leak right now. Let's break that.
Let us visualize the relationship.
There is a retain cycle. Even if you set receiverVC as nil, there is a reference count for both ReceiverVC and SenderVC from each other.
To get rid of that, make one of the relationships/references as weak.
weak references are only defined for reference types. (Closures are reference types as well, but closures cannot adopt a protocol, so they are irrelevant in this context.)
Therefore, if the object conforming to the protocol needs to be stored in a weak property then the protocol must be a class-only protocol.
Use a class-only protocol when the behavior defined by that protocol’s requirements assumes or requires that a conforming type has reference semantics rather than value semantics.
When we assign receiverVC to the nil;
- weak reference allows the referencing object to becoming nil (this happens automatically when the referenced object is deallocated)
- Based on the rule above, the referencing object/variable must be optional