Is there anything wrong in operating with ModelContainer.mainContext?

Consider this code

    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
   
    init() {
        let schema = Schema([
...
        ])

        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            sharedModelContainer = try ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
        
        SettingsViewModel.shared = SettingsViewModel(modelContext: sharedModelContainer.mainContext)
    }

I'm basically saving a copy of mainContext in a viewModel. And then later on uses that viewModel to operate on the models while using the mainActor.

Is this ok? That same container is also pass into the view using

.modelContainer(sharedModelContainer)

Can it be used in both ways like that?

Answered by DTS Engineer in 805464022

Holding the mainContext and using it later doesn't have anything wrong, in case the associated model container is valid. I typically choose to hold the model container though because:

  1. mainContext is main actor isolated. If your settings view model is a non-main actor and uses mainContext directly, the compiler may not be happy.

  2. Since you do .modelContainer(sharedModelContainer), the main context is injected to the SwiftUI environment, and is already available to the whole SwiftUI view hierarchy.

  3. You can use modelContainer.mainContext to access the main container, if needed.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Holding the mainContext and using it later doesn't have anything wrong, in case the associated model container is valid. I typically choose to hold the model container though because:

  1. mainContext is main actor isolated. If your settings view model is a non-main actor and uses mainContext directly, the compiler may not be happy.

  2. Since you do .modelContainer(sharedModelContainer), the main context is injected to the SwiftUI environment, and is already available to the whole SwiftUI view hierarchy.

  3. You can use modelContainer.mainContext to access the main container, if needed.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

@DTS Engineer

Thanks for the tips, if thats the case, operations inside the viewModel should be mainactor isolated as well right? For example

@Observable
class SettingsViewModel {
    var modelContainer: ModelContainer
    ...

    @MainActor
    func test() {
        ...
        modelContainer.mainContext.insert(model)
        modelContainer.mainContext.save()
    }

Yeah, that's right.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Is there anything wrong in operating with ModelContainer.mainContext?
 
 
Q