Created
July 9, 2020 15:13
-
-
Save Deco354/716cd67ae0f733b5cff0b330e9ab8f18 to your computer and use it in GitHub Desktop.
URLSession Lack of Retain Cycle Example
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 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