I'm having big problem with creating fetch request in my app that uses Core Data. I have 2 entities, Song and Genre. My models look like this:
I need to make query that would return top 5 played artist, using playCount attribute of Song entity. In the end I need to group result by Artist.name attribute.
I.e. resulting dictionary should look something like this:
result_array('my_first_artist' => '3200', 'my_second_artist' => '12');
I know that I can't accomplish resulting array as above in Core Data, but something similar would be great.
I tried with this code:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Artist" inManagedObjectContext:context]];
[request setPropertiesToFetch:@[@"name", @"[email protected]"]];
[request setPropertiesToGroupBy:@[@"name"]];
[request setResultType:NSDictionaryResultType];
[request setSortDescriptors:@[[[NSSortDescriptor alloc] initWithKey:@"[email protected]" ascending:NO]]];
[request setFetchLimit:5];
But it always throws exception on @"[email protected]"
part.
So my question is: How can I sum relationship objects using their attributes?
Any suggestion would be great.
EDIT:
Thanks to "Martin R" part of problem is solved. Using NSExpressionDescription
I can make fetch, but NSSortDescriptor
does not allow sorting on keys that are not attributes of NSManagedObject
entity.
In case someone needs it, this is solution:
NSExpression *aggregateExpression = [NSExpression expressionForFunction:@"sum:"
arguments:@[[NSExpression expressionForKeyPath:@"songs.playCount"]]];
NSExpressionDescription *aggregateDescription = [[NSExpressionDescription alloc] init];
[aggregateDescription setName:@"count"];
[aggregateDescription setExpression:aggregateExpression];
[aggregateDescription setExpressionResultType:NSInteger32AttributeType];
[request setPropertiesToFetch:@[@"name", aggregateDescription]];
playCount
property exists? – Zack Brown