How to access same SwiftData Model Container inside Observable Store

1.4k Views Asked by At

I am trying to access same model container inside Observable class which i have provided to Scene

var body: some Scene {
    WindowGroup {
        ContentView()
    }.modelContainer(for: [Product.self]

I can access this model inside View as following

var products: [Product]
@Query(sort: \Product.name)

AND

 @Environment(\.modelContext) private var modelContext

But how can i access same model inside

@Observable public class ProductStore{
//how to access same model context  OR
//@Query model inside this class throughs same container

}

IN CORE DATA

class PersistentStore: ObservableObject {
var context: NSManagedObjectContext { persistentContainer.viewContext }

I am wondering how i can do it in @Observable class

@Observable public class ProductStore{ // get same context as declared in App first launch }

1

There are 1 best solutions below

0
On

I do it like so

import SwiftData

@MainActor
final class SwiftDataCoordinator: NSObject {
    
    static let shared = SwiftDataCoordinator()
    
    let persistenceContainer: ModelContainer = {
        print(URL.applicationSupportDirectory.path(percentEncoded: false))
        let schema = Schema([
            YourModel.self,
            AnoterModel.self
        ])
        
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            return try ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()
    
    var modelContext: ModelContext {
        persistenceContainer.mainContext
    }
}

Later in your code you can use container to fetch your entities.

        let predicate = #Predicate<YourModel>{ object in
            object.name == name
        }
        var fetchDescriptor = FetchDescriptor(predicate: predicate)
        fetchDescriptor.fetchLimit = 1
        let items = try SwiftDataCoordinator.shared.modelContext.fetch(fetchDescriptor)
        return items.first