NSFetchedResultsController with predicate based on dependent property

cocoa, cocoa-touch, core-data, iphone

Solution

I see two solutions:

- When you modify an item have the fetched results controller perform the fetch again and reload the table view.

- Add a property to Subscription (such as your unreadCount or a boolean hasUnreadItems) and keep it properly updated. Use this property in your fetched results controller.

You can get the set of unread items for a Subscription named "aSubscription" like this:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"read == NO"];
NSSet *unreadItems = [aSubscription.items filteredSetUsingPredicate:pred];

Problem

I have a Core Data iPhone app that displays `Subscription` entities where any of its `items` are not `read`. In other words, I construct a predicate like this: ``` [NSPredicate predicateWithFormat:@"ANY items.read == NO"] ``` While this works for the initial fetch, it doesn't affect `Subscription` entities when I modify an `Item`, so the `NSFetchedResultsController` never reevaluates the `Subscription` entities. What would be a better way of structuring this so that the `Subscription` entity will be updated whenever an item's `read` property is set? I did try creating a property `unreadCount` on `Subscription` and using `keyPathsForValuesAffectingUnreadCount` to return a set containing `items.read`. I didn't expect this to work, and it didn't. I get an exception from `_NSFaultingMutableSet` telling me that the `read` key is not supported.

Original source