Skip to content

Instantly share code, notes, and snippets.

@alexnikol
Created May 2, 2020 06:18
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 alexnikol/524089be8db20b60cb3bcbd16327794c to your computer and use it in GitHub Desktop.
Save alexnikol/524089be8db20b60cb3bcbd16327794c to your computer and use it in GitHub Desktop.
Nested Functions Strong Reference Explanation
class Factory {
var car: Car
init(car: Car) {
self.car = car
}
deinit {
print("Factory model deallocated")
}
}
class Car {
var model: String
init(model: String) {
self.model = model
}
func showModel() {
print("Model \(model)")
}
func startRunProccessWeakly() {
weak var _self = self
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
_self?.showModel()
}
}
func startRunProccessStrongly() {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.showModel()
}
}
deinit {
print("Car model deallocated")
}
}
//First part with strong references
var factory: Factory? = Factory(car: Car(model: "Tesla"))
factory?.car.startRunProccessStrongly()
print("Factory try to deallocate")
factory = nil
//Second part with weak references
var factory: Factory? = Factory(car: Car(model: "Audi"))
factory?.car.startRunProccessWeakly()
print("Factory try to deallocate")
factory = nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment