SwiftData - Multiple modelContexts in one modelContainer

In the WWDC presentations, it was mentioned that you could have multiple modelContexts within one modelContainer. Does anyone know of any examples of a project with multiple modelContexts?

Specifically, I'm wondering how you distinguish between the two different modelContexts when doing things like @Query. I'd like to keep different sets of data in separate modelContexts and only Query the one that I want to pull from for a particular view.

Thanks in advance!

I haven't tried this out but I think it should work something like that:

  1. Create in your parent view the new context.
let container = try! ModelContainer(for: Model.self,
                                    ModelConfiguration(inMemory: true)) // or whatever works for you
let localContext = ModelContext(container)
  1. Then attach the localContext to a child view.
yourView
  .modelContext(localContext)
  1. In the child view you should have access to it via the environment.
@Environment(\.modelContext) var modelContext

If you want to use the same container like your original context, try originalContext.container and use that in step 1.

@Query in the child view will work on the given model context.

At least this is my theory. I don’t have time to check it, but maybe it helps you anyways.

Hi @Razorback2424 , I think that indeed, @RayWo provided you with a solution to your question, but there is something that isn't mentioned in your question, neither in the above response, which is if the queries associated with either model context will catch the updates in the model container made using the other model context. And I think that the answer is no.

As per my understanding, the model context will take care of updating the model container without collusions, but they will not read it if any update happens.

General speaking, I think that the only time that multiple Model Contex make sense is when is needed to process data of a DB in the background that doesn't care if in the meanwhile the data change and of course will never use its Model Context for data updates.

SwiftData - Multiple modelContexts in one modelContainer
 
 
Q