I created a project to test [weak self]
There is:
- main file,
- menuView, that is home view, and does only navigation to the ContentView,
- contentView, that indicates the result of resource-intensive calculation,
- and viewModel, which has a resource-intensive calculation (100 mln loop appending to the array)
So, in the code i use weak self, that makes viewModel deinizialized, when user closes the contentView. But if i open CPU graphs, there still are calculations, making to the end, even if this instance was deinizialized:
CPU and memory charts compiresment (with weak self and without)
If you compare this graphs with use of [weak self]
and without it – there is absolutaly no difference.
Here is the whole code:
struct ContentView: View {
@StateObject var vm = ViewModel()
var body: some View {
VStack {
Text("App started")
Text(vm.helloData.count.description)
}
.padding()
}
}
class ViewModel: ObservableObject {
@Published var helloData: [String] = []
init() {
print("ViewModel инициализирован")
let count = UserDefaults.standard.integer(forKey: "count")
UserDefaults.standard.set(count+1, forKey: "count")
var data: [String] = []
DispatchQueue.global().async { [weak self] in
for _ in (0..<100_000_000) {
data.append("Hello, world!")
}
DispatchQueue.main.sync {
self?.helloData = data
}
}
}
deinit {
print("ViewModel деинициализирован")
let count = UserDefaults.standard.integer(forKey: "count")
UserDefaults.standard.set(count-1, forKey: "count")
}
}
struct ContentView: View {
@StateObject var vm = ViewModel()
var body: some View {
VStack {
Text("App started")
Text(vm.helloData.count.description)
}
.padding()
}
}
struct MenuView: View {
@AppStorage ("count") var count: Int = 0
init() {
self.count = 0
}
var body: some View {
NavigationStack{
NavigationLink("go to ContentView", destination: ContentView())
}
.overlay {
VStack {
Text(count.description)
.font(.title)
Spacer()
}
}
}
}
Where am i wrong? As i understand, the reason of using weak self is to get rid of this useless calculations…
Антон Разгуляев is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.