ModelContainer working but ModelContext not finding items with SwiftDta

I am trying to count a database table from inside some of my classes. I am tying to do this below **(My problem is that count1 is working, but count2 is not working.) **

class AppState{
    private(set) var context: ModelContext?
    ....

    func setModelContext(_ context: ModelContext) {
        self.context = context
    }

    @MainActor
    func count()async{
        let container1 = try ModelContainer(for: Item.self)
        let descriptor = FetchDescriptor<Item>()

        let count1 = try container1.mainContext.fetchCount(descriptor)
        let count2 = try context.fetchCount(descriptor)

        print("WORKING COUNT: \(count1)")
        print("NOTWORKING COUNT: \(count2) -> always 0")
    }
                

I am passing the context like:

...
@main
@MainActor
struct myApp: App {

    @State private var appState = AppState()
    @Environment(\.modelContext) private var modelContext

    WindowGroup {
        ItemView(appState: appState)
            .task {
                appState.setModelContext(modelContext)
            }
    }
    .windowStyle(.plain)
    .windowResizability(.contentSize)
    .modelContainer(for: [Item.self, Category.self]) { result in 
    
    ...

}

Can I get some guidance on why this is happening? Which one is better to use? If I should use count2, how can I fix it? Is this the correct way to search inside an application using SwiftData ? I don't wanna search using the View like @Query because this operation is gonna happen on the background of the app.

Answered by SpaceMan in 799940022

I see where you define container1. You have a private var context which you never initialize like

context = ModelContext(container1).

I see where you define container1. You have a private var context which you never initialize like

context = ModelContext(container1).

ModelContainer working but ModelContext not finding items with SwiftDta
 
 
Q