Last active
February 8, 2019 17:56
-
-
Save eneko/ad6f8688caf8cea887ca99783c970edf to your computer and use it in GitHub Desktop.
Function references and retain cycles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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