Created
May 2, 2020 06:18
-
-
Save alexnikol/524089be8db20b60cb3bcbd16327794c to your computer and use it in GitHub Desktop.
Nested Functions Strong Reference Explanation
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
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