alionthego
alionthego

Reputation: 9703

How can I refresh the SwiftUI coreData @FetchRequest result?

I am using coreData and loading my model using the following:

@FetchRequest(sortDescriptors: [NSSortDescriptor(key: "dateAdded_", ascending: false)], animation: .default)
private var items: FetchedResults<Item>

The problem is when I update the one-many relation of an item and saveContext on main thread, the view is not refreshed. I'm assuming the changes to the relations are not observed.

item.addToItemRelations(itemRelation)
try? context.save()

I don't think I will be able to make this work consistently using toggle's and other hacks. Just wondering if there is anyway to force the @FetchRequest to fetch the entire result again?

Upvotes: 2

Views: 3267

Answers (1)

malhal
malhal

Reputation: 30549

If you want so show the child records then you'll need another @FetchRequest to monitor the changes of the entity of the related records using the inverse relation and parent object in the predicate. You need a child view that you supply parent item and another child view within that you init with a FetchRequest. The reason for the wrapper View is explained in this answer to a different question.

If you just want to show a computation of the child records, e.g. a count or sum, then you can first implement that using a derived attribute in the model editor. Then after the save call context.refresh(item, mergeChanges:true) and it'll reload in the object and since the derived attribute is different the @FetchRequest should detect it and cause body to be invoked.

Upvotes: 4

Related Questions