问题
I have a view that has managedObjectContext(Environment Variable). It works fine when presented in NavigationView with NavigationLink. But it does not work when the view is presented as a sheet. It gives me an error when I save some entity data.
"The operation couldn’t be completed. (Foundation._GenericObjCError error 0.)"
Is there anything I am missing when using the Environment object. My code
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
@Environment(\.managedObjectContext) var managedObjectContext
回答1:
A sheet is not a child component of the ContentView
.
Thus, you have to pass this Environment separately to the sheet:
.sheet(isPresented: self.$isPresented, content: MySheetView().environment(\.self.moc)
where moc
is defined in the View that initiates the sheet as:
@Environment(\.managedObjectContext) var moc
来源:https://stackoverflow.com/questions/59113300/environmentobject-does-not-work-when-sheet-is-presented