Hi, I am trying to create a local backup + restore when using SwiftUI and CoreData but I am facing errors left and right. the latest error I am stuck on is:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: A fetch request must have an entity.'
Here is what am trying to do:
- Creating a backup (already solved using NSPersistentStoreCoordinator.migratePersistentStore(_:to:options:type:))
- Create a new
NSPersistentContainer
and call its NSPersistentContainer.loadPersistentStores(completionHandler:) (already solved, load is successful) - Update the .environment(.managedObjectContext, viewModel.context) so that SwiftUI uses the new context. (HERE is where the error appears)
Any help would be appreciated. Here is some sample code of SwiftUI part of the main view:
class ViewModel: ObservableObject {
@Published var context: NSManagedObjectContext
}
@main
struct MyApp: App {
@StateObject var viewModel: ViewModel
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, viewModel.context)
}
}
}