After working with Core Data a little bit it and reading about it, it seems to me that passing a class around to different views is more streamlined that using @Environment(.managedObjectContext) var moc.
With the class, I can add methods to it to do the various saving, deleting, and other tasks. For instance, with the following class Paul gave us and some additions:
import CoreData
import Foundation
class DataController: ObservableObject {
let container = NSPersistentContainer(name: "Friendface")
init() {
container.loadPersistentStores { descrption, error in
if let error = error {
print("Core Data failed to load: \(error.localizedDescription)")
return
}
self.container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
}
}
func saveData() {
if container.viewContext.hasChanges {
do {
try container.viewContext.save()
} catch {
print("Save Failed! Error: \(error.localizedDescription)")
}
}
}
}
instead of writing:
if moc.hasChanges {
do {
try moc.save()
} catch {
print("Save failed! Error: \(error.localizedDescription)")
}
}
I can write:
dataController.saveData()
which seems preferred when I'm having to do it multiple times in a particular view. I do of course have to create the ObservedObject passed from wherever I initially created it, but it seems more compact and less prone to typos or missing stuff to me.
Are there disadvantages to passing the class instead of using the Environment?