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?
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:
-
mainContext
is main actor isolated. If your settings view model is a non-main actor and usesmainContext
directly, the compiler may not be happy. -
Since you do
.modelContainer(sharedModelContainer)
, the main context is injected to the SwiftUI environment, and is already available to the whole SwiftUI view hierarchy. -
You can use
modelContainer.mainContext
to access the main container, if needed.
Best,
——
Ziqiao Chen
Worldwide Developer Relations.