Created
July 13, 2016 21:11
-
-
Save jakecraige/75fe827cb800868eddf596578018435c to your computer and use it in GitHub Desktop.
Swift retrain cycle passing method to closure argument. Throw this in a playground to play around with it.
This file contains 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 Controller { | |
var changed: (() -> Void)? | |
init() { | |
print("Allocate 'Controller'") | |
} | |
deinit { | |
print("Deallocate 'Controller'") | |
} | |
} | |
class ViewController { | |
let controller = Controller() | |
init() { | |
print("Allocate 'ViewController'") | |
// controller.changed = foo // retain-cycle | |
controller.changed = { [weak self] in self?.foo() } // no retain-cycle | |
} | |
deinit { | |
print("Deallocate 'ViewController'") | |
} | |
func foo() { } | |
} | |
var vc: ViewController? = ViewController() | |
vc = nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment