views:

222

answers:

1

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:

+3  A: 
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] autorelease]]];
NSArray * result = [ctx executeFetchRequest:req error:nil];
tt.Kilew
Edited example to ged ORDER BY.In result you'll receive Array of 'SomeEntity', with different types, sorted by rank
tt.Kilew
Little fix.Edited Propertiest to fetch.
tt.Kilew
[fetchRequest setResultType:NSDictionaryResultType];Set it , and you'll receive no SomeEntity'ies in result but NSDictionary with only one fetched property @"type" in your case
tt.Kilew
Had to use setResultType, but that did it. Thanks for the solution, works well!
randombits
But I don't think that is possible to order that types by "rank" property. I think that even SQL can't
tt.Kilew