Skip to content

Instantly share code, notes, and snippets.

@vialyx
Last active April 24, 2018 12:22
Show Gist options
  • Save vialyx/195e14682c07e339203d9925d3f7eeaa to your computer and use it in GitHub Desktop.
Save vialyx/195e14682c07e339203d9925d3f7eeaa to your computer and use it in GitHub Desktop.
// MARK: - Strong reference cycle for closures
class ViewController: UIViewController {
lazy var loginCompletion: (Bool) -> Void = { success in // <- place where we has been mistaken. It must be resolved using capture list with 'unowned' reference
if success {
self.navigationController?.popToRootViewController(animated: true)
}
}
deinit {
print("ViewController was deinitialized")
}
}
var viewController: ViewController? = ViewController()
viewController!.loginCompletion
viewController = nil
/*
!!! This is strong reference cycle for closure. !!!
We have memory leak now!
*/
/*
Solution after fixes
*/
// MARK: - Resolve strong reference cycle using closure capture list
class ViewController: UIViewController {
lazy var loginCompletion: (Bool) -> Void = { [weak self] success in // We resolve memary leak just adding [weak self]
if let `self` = self, success {
self.navigationController?.popToRootViewController(animated: true)
}
}
deinit {
print("ViewController was deitialized")
}
}
var viewController: ViewController? = ViewController()
viewController!.loginCompletion
viewController = nil
/*
print: ViewController was deinitialized
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment