Created
July 9, 2020 16:16
-
-
Save Deco354/83e2b4fa27a8d43906d6f6267f722cdd to your computer and use it in GitHub Desktop.
Example showing a retain cycle only if the completionHandler of an object is explicitly stored
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
import UIKit | |
class ViewController{ | |
var networking: NetworkManager? = NetworkManager() // Unlike storedHandler this doesn't cause a leak unless it stores the completion | |
var isLoading = false | |
func loadImages() { | |
networking?.downloadImages { isSuccess in | |
self.isLoading = isSuccess | |
print("Images download completed") | |
} | |
} | |
deinit { | |
print("ViewController Deallocated") | |
} | |
} | |
class NetworkManager{ | |
var storedHandler: ((Bool) -> ())? | |
func downloadImages(completionHandler: @escaping (Bool)->()) { | |
//self.storedHandler = completionHandler // Add this line to create retain cycle | |
print("downloading images") | |
completionHandler(true) | |
} | |
} | |
var viewController: ViewController? = ViewController() | |
viewController?.loadImages() | |
viewController = nil | |
// With networkManager.storedHandler: Retain cycle | |
// completionHandler -> viewController -> networking -> completionHandler | |
// Without networkManager.storedHandler : No retain cycle | |
// completionHandler -> viewController -> networking | |
// With weak self: No retain cycle | |
// completionHandler ~> viewController -> networking -> completionHandler |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment