Capture Lists and Weak Self
Avoid retain cycles with [weak self].
The Retain Cycle Risk
When an object stores an escaping closure that captures self strongly, each keeps the other alive forever — a retain cycle that leaks memory.
A Strong Cycle
The closure captures self strongly and self holds the closure — neither is ever freed:
class Owner {
var onEvent: (() -> Void)?
func setup() {
onEvent = { print(self.describe()) } // strong self -> cycle
}
func describe() -> String { "Owner" }
}
let o = Owner(); o.setup()
o.onEvent?() // "Owner" (but leaks)All lessons in this course
- Capturing Values by Reference
- Escaping Closures
- Capture Lists and Weak Self
- Autoclosures