Delegate Retain Cycle in Swift

Kaan Vural
Mac O’Clock
Published in
2 min readMay 17, 2020

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.

Object will be created and there will be memory leak.

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.

It forces us to add class-only conformance to related protocol

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.

Current relationship

When we assign receiverVC to the nil;

There will be no memory leak.
  • 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

--

--