Reputation: 3939
I have a NSFetchRequest (executing in a NSFetchedResultsController) for the following data:
Person (one-to-many) Encounter
Encounter has an int field "type". In my tableView, I want to show:
Person A - Encounter of type 1
Person A - Encounter of type 2
Person B - Encounter of type 1
etc. That is, for a Person, I only want one Encounter of each type. Is there a way to do that in a Core Data query? I could do this with code to filter the result of an NSFetchRequest, but then I couldn't use NSFetchedResultsController.
[EDIT]
Here's the code I'm currently trying. The result is several Encounters with the same type for one Person.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// entity
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Encounter" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// return distinct
NSDictionary *entityProperties = [entity propertiesByName];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:
[entityProperties objectForKey:@"person"],
[entityProperties objectForKey:@"type"],
nil]];
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setResultType:NSDictionaryResultType];
NSError *error;
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSDictionary *d in fetchedObjects) {
NSLog(@"NSDictionary = %@", d);
}
[fetchRequest release];
Upvotes: 0
Views: 3026
Reputation: 80271
I am assuming you want to return just one record for each type of Encounter even if a Person has more than one of any given type. You can accomplish this by adjusting your NSFetchRequest
accordingly:
[fetchRequest setReturnsDistinctValues:YES];
Upvotes: 1