The Problem:
In SwiftUI, when dismissing a sheet, associated instances (view models held by the sheet’s view) don’t seem to get deinitialized as expected. This issue is observed with @ObservedObject
and the new @Observable
macro but not with @StateObject
. This behavior results in memory leaks and creates challenges in ensuring proper cleanup and resource management within the view models.
Q&A
When I use @ObservedObject or the new @Observable macro in SwiftUI, associated instances don’t seem to get deinitialized properly upon sheet dismissal. Why?
@StateObject is the only method that properly triggers the deinit
call for associated instances in SwiftUI sheets.
Is there a workaround for this issue?
No known workarounds, though you can inform the view model about the dismissal to make it stop long-running tasks.
When is this issue resolved?
The issue is resolved on iOS 17.2.