0

I just do some experiments in my pet project on iOS 16 Beta. I noticed one possible memory leak. I created a simple project with simple steps which reproduce this behavior. So I have ContentView and DetailView I use NavigationStack for navigation. I created DetailViewModel for DetailView and add it as @StateObject and also add it as environmentObject for DetailView subviews. All good as expected but if I present/show PhotosPicker and return back to ContentView I can see that DetailViewModel isn't deinit. Is it memory leak? How can we fix/avoid this? Thanks.

Below I added code from the simple project also for convenience you can have a have look on GitHub

ContentView:

struct ContentView: View {
    var body: some View {
        NavigationStack {
            let route = Route.detail
            NavigationLink("Show Detail", value: route)
                .navigationDestination(for: Route.self) { route in
                    switch route {
                    case .detail:
                        DetailView()
                    }
                }
        }
    }
}

Route:

enum Route: Hashable {
    case detail
}

DetailView:

import SwiftUI
import PhotosUI

struct DetailView: View {
    @StateObject private var viewModel = DetailViewModel()
    // just for test
    @State private var photoPickerPresented = false
    @State private var selectedPickerItem: PhotosPickerItem?

    var body: some View {
        VStack {
            Button {
                photoPickerPresented.toggle()
            } label: {
                Text("Show Photo Picker")
            }
        }
        .photosPicker(isPresented: $photoPickerPresented, selection: $selectedPickerItem)
        .environmentObject(viewModel)
    }
}

DetailViewModel:

class DetailViewModel: ObservableObject {
    init() {
        debugPrint("DetailViewModel init")
    }

    deinit {
        debugPrint("DetailViewModel deinit")
    }
}
Alexander Khitev
  • 6,417
  • 13
  • 59
  • 115
  • why would you want a view model object in SwiftUI in the first place? The View struct is already the model for the UIViews it generates. – malhal Aug 28 '22 at 19:58
  • I do some tests/experiments with SwiftUI and just try to understand this behavior (find information about it) – Alexander Khitev Aug 28 '22 at 20:01
  • I had the same problem here: https://stackoverflow.com/questions/71674556/deinit-not-called-when-using-uiimagepickercontroller-in-swiftui. Do you have a solution? – J. Doe Oct 05 '22 at 12:27
  • Hey @J.Doe! Not for now. this is a very interesting issue – Alexander Khitev Oct 05 '22 at 13:44

0 Answers0