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 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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With