This simple example is leaking memory. Especially when the button is pressed.
I think it's got something to do with the way I'm creating the ViewModel.
Please could someone kindly tell my why and how to fix it.
// MyTestApp.swift
@main
struct MyTestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
// ContentView.swift
struct ContentView: View {
@StateObject var vm = ViewModel()
@State var tog = false
var body: some View {
VStack {
Text(vm.myObject.number)
.padding()
Button(action: {
vm.toggleButton(truth: tog ? "True" : "False")
tog.toggle()
}, label: {
Text("Toggle")
})
Text(vm.myObject.truth)
.padding()
}
.frame(width: 300, height: 200)
.environmentObject(vm)
}
}
// ViewModel.swift
struct MyObject {
var number = ""
var truth = ""
}
class ViewModel: ObservableObject {
@Published var myObject = MyObject()
private var timer: Timer?
init() {
timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [self] timer in
getRandonNumber()
}
}
func getRandonNumber() {
let n = Int.random(in: 100...999)
myObject.number = "number is \(n)"
}
func toggleButton(truth: String) {
myObject.truth = truth
}
}
Having experimented with every conceivable variation of this very simple app, I can only conclude the problem is within Apple's Swift Compiler. It's a compiler bug they don't tell us about. I suspected every app in the App Store is also eating memory without releasing it. Nobody cares or even notices, because the idiots who have the iPhone glued to their hands only use these app for a short time. Try developing a real app for macOS with lots of buttons and this issue becomes very serious.
So I've answered my own question.
I'm currently developing on Big Sur. Can anyone tell me if Apple have fixed this in any of the latest beta versions?