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
}
}
-
—
OOPer
Add a CommentI have tried your code with Leaks and no memory leak is reported even if I tap the button hundreds of times. Can you clarify how you have checked it and how to reproduce the issue?