aaronfalls
aaronfalls

Reputation: 201

Get unique objects at end of relationship for fetch results

In my app, I have two entities, Page and Annotation. In my Core Data model, they have a one to many relationship: Page <-->> Annotation.

I am fetching on the Annotation object because I need to apply certain predicates, but ultimately want to get a unique set of Pages that are related to the Annotations that match the predicate.

How can I get a set of unique Page objects that have a relationship to the Annotations returned from the fetch? Is it possible to do it in one fetch? I have tried some things with NSDictionaryResultType but got errors, and ultimately, I want objects, not values.

Upvotes: 3

Views: 414

Answers (1)

Marcus S. Zarra
Marcus S. Zarra

Reputation: 46718

You do not want to use NSDictionaryResultType as that does not return objects. What you want to do is use KVC after you have retrieved your Annotation instances like this:

NSArray *results = ...; //Your fetch of Annotation objects
NSArray *uniquePages = [results valueForKeyPath:@"@distinctUnionOfObjects.page"];

The uniquePages array will contain your unique collection of Page instances.

Upvotes: 7

Related Questions