Skip to content

Instantly share code, notes, and snippets.

@Deco354
Created July 9, 2020 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deco354/83e2b4fa27a8d43906d6f6267f722cdd to your computer and use it in GitHub Desktop.
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
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