Update SwiftUI View after updating core data value with toggle button

In SwiftUI, I have a simple core data entity, and one of the attributes called "finished" (Bool).


I fetch the core data to create a List in ListView. When I click an item of the List, it goes to the DetailView, which includes the record "finished".



In the DetailView, I added a toggle button to SHOW the value of "finished", and meanwhile I use this toggle button to UPDATE the record of "finished" in core data.


The curent problem is I can use this toggle button to CHANGE the record in core data; however, the result CANNOT be updated immediately in DeailView. (That means, when I go back to ListView, I see it's updated. And when I click the item and go to DetailView, the record's also properly shown.)


1) How to fix this issue? What's the best way to do it?

2) What's the proper way to assign the core data value of "finished" to the toggle button, when DetailView's launched?


I'm new to Swift, and very grateful for anybody's help.

I Had a similar issue when passing a Core Data value between views.


if I recall correctly I solved it by also including the @Environment(\.managedObjectContext) (possibly also the @FetchRequest as well) into the DetailView. When toggling the value the view then updated once the managed object was saved to the context.

Actually in ListView, I've already put the two items you mentioned. In DetailView, and I've also inserted @Environment(\.managedObjectContext) in DetailView.


Now the only problem is the record of core data is updated in DetailView, but it can't refresh and show the correct result.


I tried the way you said to includ @FetchRequest, but there's some error message.

I use relationships and when I delete some items from a list, the data are deleted from the database but they are not removed from the list.

I use a simple workaround:
After saving the data, I reload the view.

Code Block SwiftUI
import SwiftUI
struct CustomView: View {
...
var body: some View {
... 
do {
try self.managedObjectContext.save()
CustomView()
} catch {
...
}
}
}

Update SwiftUI View after updating core data value with toggle button
 
 
Q