Skip to content

Instantly share code, notes, and snippets.

@jakecraige
Created July 13, 2016 21:11
Show Gist options
  • Save jakecraige/75fe827cb800868eddf596578018435c to your computer and use it in GitHub Desktop.
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.
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