Skip to content

Instantly share code, notes, and snippets.

@eneko

eneko/retain_cycles.swift

Last active Feb 8, 2019
Embed
What would you like to do?
Function references and retain cycles
class MyClass {
var foo: () -> Void = {}
init() {
foo = defaultFoo
}
private func defaultFoo() {
print("Foo Bar")
}
deinit {
print("MyClass Released 🎉") // Never gets called, retain cycle
}
}
class MyClassNested {
var foo: () -> Void = {}
init() {
func defaultFoo() {
print("Foo Bar Nested")
}
foo = defaultFoo
}
deinit {
print("MyClassNested Released 🎉") // Gets called
}
}
var normal: MyClass? = MyClass()
var nested: MyClassNested? = MyClassNested()
normal?.foo() // prints: Foo Bar
nested?.foo() // prints: Foo Bar Nested
normal = nil // deinit does not get called
nested = nil // prints: MyClassNested Released 🎉
// Alternatively, this code is simpler, but deinit is called first because the instance is released right away
MyClass().foo() // deinit does not get called
MyClassNested().foo() // deinit gets called
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment