Skip to content

Instantly share code, notes, and snippets.

@alexnikol

alexnikol/.swift

Created May 2, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.