Reference Cycles in iOS
Strong reference cycles prevent instances from ever being deallocated, causing a memory leak. There are two ways of breaking the cycle - using weak
or unowned
for one of the instances.
-
weak
reference - should be used when the other instance has a shorter lifetime. ARC will set its value to nil when there are nostrong
references to it. -
unowned
reference - should be used when the other instance has the same or longer lifetime. Unowned reference is expected to always have a value. ARC won’t set its value to nil.
Important
It is crucial to be aware that the property observers won’t be called when weak
reference is set to nil
.
“Property observers aren’t called when ARC sets a weak reference to nil.” - The Swift Programming Language (Swift 5.7), Apple Inc. Reference