Retain cycles & breaking with weak/unowned
Spot retain cycles between objects and closures, then break them using weak and unowned references safely.
What is a retain cycle?
A retain cycle happens when objects (or closures) keep strong references to each other so ARC never reaches zero. Break cycles with weak or unowned.
Object ↔ object cycle
Two strong references in both directions create a leak: neither object can drop to zero.
final class Owner {
var gadget: Gadget?
deinit { print("Owner deinit") }
}
final class Gadget {
var owner: Owner?
deinit { print("Gadget deinit") }
}
// Strong ⇄ strong (cycle)
var o: Owner? = Owner()
var g: Gadget? = Gadget()
o!.gadget = g
g!.owner = o
o = nil // no deinit
g = nil // still no deinit (leak)All lessons in this course
- ARC basics: strong / weak / unowned
- Retain cycles & breaking with weak/unowned
- Value types to reduce sharing