Last active
April 24, 2018 12:22
-
-
Save vialyx/195e14682c07e339203d9925d3f7eeaa to your computer and use it in GitHub Desktop.
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
// 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