Post

Replies

Boosts

Views

Activity

Does SwiftUI cache images in memory?
I have a VStack of views where each view contains an ArtworkView: struct ArtworkView: View {   let artworkId: UInt64   @State private var uiImage: UIImage?   @Environment(\.scenePhase) var scenePhase   @ViewBuilder var imageView: some View {     if let uiImage = uiImage {       Image(uiImage: uiImage)     }     else {       Image(systemName: "photo").opacity(0.4)     }   }   var body: some View {     imageView       .onAppear() {         loadArtwork(withId: artworkId) {           uiImage = $0         }       }       .onChange(of: scenePhase) { scenePhase in         if scenePhase == .background {           uiImage = nil         }       }   } } At first sight it works as expected – images appear on launch and disappear upon transition to the background. But when I profile with Instruments > Allocations there is no difference in memory usage between foreground and background. And I need images to be unloaded from memory in background. Does SwiftUI VStack or Image cache underlying UIImage objects and if so, how to opt out of it?
0
0
1.1k
Jun ’21
@Observable/@State memory leak
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.
7
10
3.5k
Aug ’23