Skip to content

Instantly share code, notes, and snippets.

@Deco354
Created July 9, 2020 16:16
Show Gist options
  • Save Deco354/5fbcd74b2cfbc4bcc75a337f0e157c1a to your computer and use it in GitHub Desktop.
Save Deco354/5fbcd74b2cfbc4bcc75a337f0e157c1a to your computer and use it in GitHub Desktop.
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