@FetchResults doesn't refresh view when updating related fields

If I query an entity with a relationship to another entity, and then I update that related entity, the view does not refresh automatically. I'm 'forcing' it now, but that doesn't seem right. What's the right way?

See code sample:

Code Block swift
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [],
animation: .none)
private var categories: FetchedResults<Category>
private func forceRefresh() {
viewContext.refresh(categories[0], mergeChanges: true)
}
var body: some View {
VStack {
List {
ForEach(categories) { category in
Section {
Text("\(category.name!)").font(.title)
}
ForEach(category.items?.allObjects as! [Item]) { item in
Button {
item.name = "\(UUID())"
} label: {
Text("\(item.name!)").font(.caption)
}
}
}
}
Divider()
Button {
forceRefresh()
} label: {
Text("Force Refresh").foregroundColor(.blue)
}
}
}
}


hi,

when a Category has a to-many relationship with an Item, and you edit an attribute of an Item, the item will do an objectWillChange.send(). but your @FetchRequest setup is only responding to changes to Categories.

one possible suggestion: on line 26 when you change the name of an item, insert a line in advance of the name change (between line 25 and line 26) to tell your View that the content it is displaying needs to be recomputed:

Code Block
category.objectWillChange.send()

i think that will work -- but full disclosure: i did not test.

hope that helps,
DMG

BTW: thanks for asking. turns out i had something like this in one of my projects and realized when i read your question that i had the same situation in one case. sure enough -- one piece of a display was not updating after editing the "Items" associated with a "Category." i used essentially the idea above, although the technique was a little different.
@FetchResults doesn't refresh view when updating related fields
 
 
Q