I got the exact same error message and resolved it by changing the way I create and keep my ModelContainer.
Before, I created it in ContentView like this:
NavigationStackView()
.modelContainer(MyModelContainer.create())
and accessed it in all other views via
@Environment(\.modelContext) private var modelContext
MyModelContainer.swift looked like this:
actor MyModelContainer
{
@MainActor static func create() -> ModelContainer
{
let schema = Schema([MyModel.self])
let configuration = ModelConfiguration("foo", url: FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!.appendingPathComponent("foo.store"))
let container = try ModelContainer(for: schema, configurations: [configuration])
// ... fill it ...
SomeSingleton.shared.modelContext = container.mainContext // Other classes need model access too
return container
}
}
I have 2 models, but I've ruled that out as a cause. I also ruled out that @Environment causes it, because the crash happened even if only my SomeSingleton
accessed the modelContext.
For me, the solution was to make container
a member of MyModelContainer
, which I turned into a Singleton:
@MainActor class MyModelContainer
{
static let shared = MyModelContainer()
let container: ModelContainer
private init()
{
let schema = Schema([MyModel.self])
let configuration = ModelConfiguration("foo", url: FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!.appendingPathComponent("foo.store"))
container = try ModelContainer(for: schema, configurations: [configuration])
// ... fill it ...
}
}
In other places (another Swift class, and SwiftUI), I access it via MyModelContainer.shared.container.mainContext
. In SwiftUI, I removed all .modelContainer
and @Environment
lines. I suppose that these modifications might have also improved the thread safety and performance of my code, Apple probably had a reason for this change.
I'll also file a bug report as soon as I find the time to build a minimal example project.
Hope that helps 🙂