Unexpected Memory Leak in SwiftUI – Any Tips?

Hi everyone,

I’ve been working on a SwiftUI app and noticed an unexpected memory leak when using @StateObject inside a View. Even after the view is dismissed, the object doesn’t seem to deallocate properly.

I’ve tried:

  • Using @ObservedObject instead of @StateObject
  • Manually setting the object to nil
  • Checking for strong reference cycles

Has anyone else encountered this? What’s the best way to ensure proper deallocation in SwiftUI?

Thanks in advance!

I might suggest you include a small reproducible example of the problem, as this is a little hard to answer in the abstract. I might also suggest including information about what version of Xcode you are using (some early versions of SwiftUI had issues where views were not deallocated when one might have otherwise expected; for performance reasons, I believe). But, I tried manifesting the problem with the latest version of Xcode (something that I historically saw behavior like you described), but was unsuccessful. So a little more information might help us help you better.

FWIW, I also might suggest the Apple’s developer forums, as that might be a better forum for Apple framework questions.