iosmacoscore-dataios5fetched-property

Fetched Property in core data returning improper count


I have a core data relationship that looks like this

ItemA ->> ItemB

where as itemA has many of itemB. i wanted to use a fetched property that allowed me to grab all associated of itemB that were associated with itemA that had an int32 status property set as "2". So i created a fetched property in the data modeler that had the following:

fetched property: completedItem predicate: status == 2 destination: itemB

when i first tried it out, i got items back and i thought that was all cool and done, then later i noticed odd behavior and when i looked closer the items that it returned had nothing to deal with actual amount of itemB that was associated with an itemA object. Even weirder is that the return type is NSFaultingMutableArray. Here's a quick example

This is just weird in my head right now and really isn't making sense. any ideas?

UPDATE 1:

it appears the fetched property listed here gets all ItemB objects that core data has to offer that matches the predicate, even if it's not associated with the ItemA in question


Solution

  • Here's the answer to this all the weirdness in this issue:

    1) The fetched properties indeed were not returning ItemB objects just for ItemA. In order for this to occur, you have to add something like this in the fetched properties predicate

    status == 2 AND ItemA == $FETCH_SOURCE
    

    2) From the Fetched Properties documentation:

    A fetched property is evaluated lazily, and is subsequently cached.

    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.

    so basically use refreshObject:mergeChanges to manually refresh the object to reload the fetched property. you can do this by adding a refresh method or by doing some fancy overriding to the KVC get method inside your subclassed NSManagedObject.

    This being said, others here (Rob Booth, Grady Player), have other valid solutions by bypassing fetched properties entirely. While these are faril