Not sure if this code is supposed to leak memory or am I missing something?
import SwiftUI
import Observation
@Observable class SheetViewModel {
let color: Color = Color.red
init() { print("init") }
deinit { print("deinit") }
}
struct SheetView: View {
@State var viewModel = SheetViewModel()
var body: some View {
Color(viewModel.color)
}
}
@main
struct ObservableMemoryLeakApp: App {
@State var presented: Bool = false
var body: some Scene {
WindowGroup {
Button("Show") {
presented = true
}
.sheet(isPresented: $presented) {
SheetView()
}
}
}
}
Every time the sheet is presented/dismissed, a new SheetViewModel
is created (init is printed) but it never released (deinit not printed). Also, all previously created SheetViewModel
instances are visible in Memory Graph and have "Leaked allocation" badge.
Reverting to ObservableObject/@StateObject
fixes the issue, deinit is called every time the sheet is dismissed:
-import Observation
-@Observable class SheetViewModel {
+class SheetViewModel: ObservableObject {
- @State var viewModel = SheetViewModel()
+ @StateObject var viewModel = SheetViewModel()
Does this mean there's a bug in Observation
framework?
Reported as FB13015569.