Retrieving a unique result set with Core Data
- by randombits
I have a core data based app that manages a bunch of entities. I'm looking to be able to do the following.
I have an entity "SomeEntity" with the attributes: name, type, rank, foo1, foo2.
Now, SomeEntity has several rows if when we're speaking strictly in SQL terms. What I'm trying to accomplish is to retrieve only available types, even though each instance can have duplicate types. I also need them returned in order according to rank. So in SQL, what I'm looking for is the following:
SELECT DISTINCT(type) ORDER BY rank ASC
Here is the code I have so far that's breaking:
NSError *error = NULL;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"type", @"rank", nil]];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"SomeEntity" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// sort by rank
NSSortDescriptor *rankDescriptor = [[NSSortDescriptor alloc] initWithKey:@"rank" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:rankDescriptor,nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[rankDescriptor release];
NSArray *fetchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
return fetchResults;
Right now that is crashing with the following: Invalid keypath section passed to setPropertiesToFetch: