EnvironmentObject does not work when sheet is presented

老子叫甜甜 提交于 2021-01-29 18:52:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!