I don't really understand how the environment works when using modals. It looks like the environment is separated for modal views.
I made a quick example using core data and saving an object to Core Data. If I do not pass the environment, then the object does not get saved and I get the following error when trying to save the object: The operation couldn’t be completed. (Foundation._GenericObjCError error 0.)
If I pass the managed object context in the modal's environment it works. I commented out the line that makes it work.
Can anyone explain why does this happen, please?
@FetchRequest(fetchRequest: ToDoItem.fetchAllItems()) var items
@Environment(\.managedObjectContext) var managedObjectContext
@State var showAddModal = false
var body: some View {
VStack {
List(items, id: \.name) { item in
Text(item.name)
}
Button(action: {
self.showAddModal.toggle()
}) {
Text("Add item")
}.sheet(isPresented: $showAddModal) {
ModalView()
// .environment(\.managedObjectContext, self.managedObjectContext)
// It works if the managed object context is passed in the modal's environment
}
}
}
}
struct ModalView: View {
@State var toDoItemName: String = ""
@Environment(\.presentationMode) var presentationMode
@Environment(\.managedObjectContext) var managedObjectContext
var body: some View {
VStack {
TextField("Item name", text: $toDoItemName)
Button(action: {
let toDoItem = ToDoItem(context: self.managedObjectContext)
toDoItem.name = self.toDoItemName
do {
try self.managedObjectContext.save()
} catch {
print(error.localizedDescription)
}
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Add")
}
}
}
}```