SwiftUI CoreData NSManagedObjectContext in the Environment
Figured out what's causing both error messages here. The first error is coming from my PersistentContainer
singleton. I moved the two lines configuring the viewContext
into the loadPersistentStores
completion block, and those warnings went away:
private convenience init() {
self.init(name: "App")
loadPersistentStores { description, error in
viewContext.mergePolicy = NSMergePolicy(merge: .mergeByPropertyStoreTrumpMergePolicyType)
viewContext.automaticallyMergesChangesFromParent = true
if let error = error {
fatalError("Unable to load persistent stores: \(error)")
}
}
}
The second issue is apparently an issue with SwiftUI since the betas. There's a thread about it on the Apple Dev Forums here. You can do this as a workaround:
.sheet(isPresented: $isPresentingCategoryPicker) {
CategoriesView()
.environment(\.managedObjectContext, self.context)
}
It seems the environment gets cleared for modally presented view controllers.