Skip to content

Instantly share code, notes, and snippets.

@Deco354
Created July 9, 2020 15:13
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/716cd67ae0f733b5cff0b330e9ab8f18 to your computer and use it in GitHub Desktop.
Save Deco354/716cd67ae0f733b5cff0b330e9ab8f18 to your computer and use it in GitHub Desktop.
URLSession Lack of Retain Cycle Example
import Foundation
class ViewController{
var networking = URLSession.shared
var isLoading = false
func loadImages() {
print("loading images")
networking.dataTask(with: URL(string: "https://deckofcardsapi.com/api/deck/new/draw/?count=52")!) { (_, _, _) in
print("Load Complete")
self.isLoading = true
}.resume() //Remove this and ViewController won't deallocate because the completionHandler keeps it alive
}
deinit {
print("ViewController Deallocated")
}
}
var viewController: ViewController? = ViewController()
viewController?.loadImages()
viewController = nil
// No Retain Cycle
// dataTask.completionHandler -> ViewController -> URLSession -> URLSessionDataTask
// However the ViewController will be kept in memory as long as the completionHandler is kept in memory so it won't deallocate if the completionHandler is never called (i.e. we don't resume the data task)
// If we use weak self the ViewController will be dismissed immediately when we set it to nil without waiting for the dataTask CompletionHandler to be called and deallocated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment