1

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?

alionthego
  • 8,508
  • 9
  • 52
  • 125

1 Answers1

4

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.

malhal
  • 26,330
  • 7
  • 115
  • 133
  • sorry, did you mean context.refresh(item, mergeChanges: true)? because the NSManagedObject item doesn't have a refresh property as far as I can see. For context.refresh(item.. that didn't work for me. – alionthego Feb 12 '22 at 09:29
  • oh sorry you're right that won't work. I've updated my answer with another possible solution – malhal Feb 12 '22 at 09:57