does anyone have a working example of a fetched-property in core-data?

后端 未结 3 777
广开言路
广开言路 2021-01-31 18:08

I have tried to use fetched properties a couple of times, and although it seems to be the right approach, it never works.

In my latest attempt I added the fetch

3条回答
  •  再見小時候
    2021-01-31 18:34

    Here's my relevant bits of code (including bits you've already mentioned):

    My example has a 'Card' object that has a 1->many relationship with a 'Stats' object. Each 'Stats' object has an 'outcome' that can be 1-4. My fetched property is a simple one to give my 'Card' object an array of 'Stats' objects that are of 'outcome'=1 only.

    I wanted to use the fetched property so that I could easily get hold of 'Card' objects that had more than a certain number and kind of 'Stats' objects.

    So, in the 'Card' object I put the Fetched Property 'statsOfTypeOne', with Destination set to 'Stats'.

    In the predicate for this fetched property I put

    (SELF.outcome=1) AND (SELF.card=$FETCH_SOURCE)
    

    'SELF' is the 'stats' record, and $FETCH_SOURCE magically becomes the 'Card' object when executed.

    As you did, I put the following in the .h and .m files for the 'Card' object:

    @property (nonatomic, retain) NSArray *statsOfTypeOne;
    @dynamic statsOfTypeOne;
    

    Then in my code I used:

    [self.managedObjectContext refreshObject:cardInstance mergeChanges:YES];
    [cardInstance valueForKey:@"statsOfTypeOne"]
    

    to get at the array (although cardInstance.statsOfTypeOne should be fine). Without the refresh object it wasn't updating the Fetched property (as per the manual).

    I think that's everything that I did to make it work. Let me know if it works for you.

    Peter

提交回复
热议问题