0

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

}

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
shoji
  • 103
  • 3
  • 1
    Dependency injection, you could pass the model container or context to the init of the observable type or pass the model context from the view in each function call. – Joakim Danielson Aug 12 '23 at 10:21
  • What do u mean by each function call ? why not one time inside swiftUI init – shoji Aug 13 '23 at 01:04
  • It depends on what suits you best, I don’t know your code so it was just an example. Anyway, this isn’t much different using Core Data with SwiftUI and a StateObject so you could look for examples doing that as well – Joakim Danielson Aug 13 '23 at 05:57
  • @JoakimDanielson What about instantiate a `ModelContainer` inside `@Observable` object `ProductStore` and set it in the app environment `.modelContainer(productStore.container)` ?!?! – quaternionboy Aug 15 '23 at 12:36
  • i noticed multiple ModelContainer cause issues while CRUDT operations. – shoji Aug 15 '23 at 13:32
  • @quaternionboy I tried briefly to use two model containers but also ran into some issues and even if it would work I assume it meant that you manually need to keep them in sync. – Joakim Danielson Aug 15 '23 at 13:42

0 Answers0