I've an Core Data entity called "Themes" with 4 properties. One of them is called "name". This property is not unique. I would like to retrieve a list of all the names contained in the data.
It seems that I need to use the setReturnesDistinctResults:YES option of the fetch request but I can't make it work. Is there anything wrong in the code below?
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// entity
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Themes" inManagedObjectContext:_context];
[fetchRequest setEntity:entity];
// sort descriptor
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// return distinct
NSDictionary *entityProperties = [entity propertiesByName];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:[entityProperties objectForKey:@"name"]]];
[fetchRequest setReturnsDistinctResults:YES];
NSError *error;
NSArray *fetchedObjects = [_context executeFetchRequest:fetchRequest error:&error];
for (Themes *theme in fetchedObjects) {
NSLog(@"Theme = %@", theme.name);
}
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];