Before you begin I highly recommend you to check ARC story.
We will begin with checking no memory leak case in closures;
The closure block is separate from the Human object and the humanClosure property has a reference to the closure block.
Since the Human object as one reference from the kaan property, we able to deallocate.
The closure block has been also deallocated due to the reference count of zero.
Now, check below case.
Let us visualize the relationship to see the retain cycle.
To overcome the result above, we must use capture lists. You will capture self as a weak reference.
Be careful when you use self keyword in closure. (indicates there may be a retain cycle)
However, the capture self within the closure has turned into an optional type. Let us review the rule of weak.
- A 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