Thanks @AlbertUI. I like your implementation in a singleton pattern. However I get the following error:
MainView().environment(\.managedObjectContext, PersistentStore.shared)
Error: > Cannot convert value of type 'PersistentStore' to expected argument type 'NSManagedObjectContext'
My implementation looks like this:
import Foundation
import CoreData
final class PersistentStore: ObservableObject {
@Published var accounts = [Account]()
static let shared = PersistentStore()
private init() {
fetchEntries()
}
func fetchEntries() {
let moc = persistentContainer.viewContext
let request: NSFetchRequest<Account> = Account.fetchRequest()
do {
let accountsCoreData = try moc.fetch(request)
accounts = accountsCoreData
} catch {
print("Fetch failed: Error \(error.localizedDescription)")
accounts = []
}
}
var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Model")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}