2
votes

I have these 2 Core Data entities :

1) Contact : name / ... / history (To many relationship with the 'Event' entity)

2) Event : date / contact (To one relationship with the 'Contact' entity)

contact is the inverse of history (and vice versa)

Now I want to retrieve the contact property of all the events sorted by the date property and without contact duplicates.

I have tried these 2 approaches without success :

// This is a fetch request for the 'Event' entity
NSFetchRequest *contactsRequest = ...

1)

[contactsRequest setPropertiesToFetch:@[@"contact"]];
[contactsRequest setReturnsDistinctResults:YES];
[contactsRequest setResultType:NSDictionaryResultType];
[contactsRequest setSortDescriptors:@[[[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO]]];

Here the contacts are unique but the sort descriptor is just ignored, because I don't fetch the 'date' property.

2) So I changed line 1 to

[contactsRequest setPropertiesToFetch:@[@"contact", @"date"]];

Now it's the other way around, the contacts are not unique (it's the (contact,date) pair that's unique), but the results are sorted.

I just can't figure out how to have both unique and sorted contacts. Thanks for your help.

1
BTW, you ought to be passing NSPropertyDescription objects to setPropertiesToFetch: according to the referenceDavid Berry

1 Answers

0
votes

Use returnsDistinctResults to fetch only the distinct results, unsorted. Then use sortedArrayUsingDescriptors: to sort the results.