Problem
- For a mac app, when the Settings view that uses
@Environment(\.dismiss)it causes the subview's models to be created multiple times.
Environment
- macOS: 26.2 (25C56)
Feedback
- FB21424864
Code
App
@main
struct DismissBugApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
Settings {
SettingsView()
}
}
}
ContentView
struct ContentView: View {
var body: some View {
Text("Content")
}
}
SettingsView
struct SettingsView: View {
@Environment(\.dismiss) private var dismiss
var body: some View {
VStack {
Text("Settings")
SectionAView()
}
}
}
SectionAView
struct SectionAView: View {
@State private var model = SectionAViewModel()
var body: some View {
Text("A")
.padding(40)
}
}
SectionAViewModel
@Observable
class SectionAViewModel {
init() {
print("SectionAViewModel - init")
}
deinit {
print("SectionAViewModel - deinit")
}
}
Steps to reproduce (refer to the attached video)
1 - Run the app on the mac
2 - Open app's Settings
3 - Notice the following logs being printed in the console:
SectionAViewModel - init
SectionAViewModel - init
4 - Tap on some other app, so that the app loses focus
5 - Notice the following logs being printed in the console:
SectionAViewModel - init
SectionAViewModel - deinit
6 - Bring the app back to focus
7 - Notice the following logs being printed in the console:
SectionAViewModel - init
SectionAViewModel - deinit
Refer to screen recording