How do ensure that a Core Data Fetched Property is fetched from the context rather than the cache?

StackOverflow https://stackoverflow.com/questions/3778666

Question

I have a managed Object Model that contains 2 Entities.

One of the entities (Lets Call it EA) calculates it's properties by referencing some properties in a sub-set of the second entity (Call it EB).

Within EA I have set up a "Fetched Property" with a predicate that returns the subset of EB objects that I need.

When I Delete, Insert an EB object or change an EB Object I use notifications to ensure that EA is kept up to date. So for example after a "save" the EA object will recalculate it's properties.

My problem is that when I access the Fetched Property (Which I do within the EB model class using [self valueForKey:FetchedPropertyKeyName]), It appears only to extract the cached version. In other words the first time is fine, but when I add another EA object I am not seeing it in the returned array when I access the fetched property. This is most obvious when I delete an object, as then I get a crash due to the fact that this object no longer exists.

The documentation for Fetched Properties says:

If objects in the destination entity are changed, you must reevaluate the fetched property to ensure it is up-to-date. You use refreshObject:mergeChanges: to manually refresh the properties—this causes the fetch request associated with this property to be executed again when the object fault is next fired.

Sorry if it sounds a dumb question but unfortunately I'm not seeing where I should call refreshObject:mergeChanges: ??

Was it helpful?

Solution

The discipline of writing the question made me look closely at the code again so I now have a solution!

I added:

[[self managedObjectContext] refreshObject:self mergeChanges:YES];

Into the Observing methods. This causes a fetch to occur, and it's in the awakeFromFetch method that I re-evaluate all my properties and the fetched property now contains the new data as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top