Retrieving a unique result set with Core Data
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, fo开发者_运维百科o1, foo2.
Now, SomeEntity has several rows if 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:
NSManagedObjectContext * ctx ; /* some ctx */
NSFetchRequest * req; /* your request */
NSEntityDescription *entity = [NSEntityDescription entityForName:@"SomeEntity" inManagedObjectContext:context];
NSDictionary *entityProperties = [entity propertiesByName];
[req setEntity:entity];
[req setReturnsDistinctResults:YES];
[req setPropertiesToFetch:[NSArray arrayWithObject:[entityProperties objectForKey:@"type"]]];
[req setSortDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"rank" ascending:YES]]];
NSArray * result = [ctx executeFetchRequest:req error:nil];
精彩评论