Group and sum several records using Core Data
I'm looking for an efficient way to do this. I have an entity with 2 attributes: isPrivate and points. isPrivate may have one of two values: y or n. Points, a number in the range of -200 to 200.
I need to group an sum the points in the following way:
-200 to 0: 340pts
0 to 100: 231pts
100 to 200: 987pts.
I'm currently running a predicate to get the records, one for each range I need:
...
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isPrivate = %y"];
...
NSArray *ks = [[NSArray alloc] initWithArray:[context executeFetchRequest:fetchRequest error:&error]];
NSNumber *t = [ks valueForKeyPath:@"@sum.points"];
...
and it works, but I'm looking for a better way to do it.
First, In the way I'm doing it, I'm loading the records in memory, th开发者_JS百科en in a NSArray. If I could avoid that, would be perfect Secondly, If I could do it in one step, it may be better.
The perfect solution for this would be a way to group and sum the records in a single predicate, don't load the records in memory and only get the sum, not all the dat.
tks.
I think you want to fetch specific values using an NSExpression.
This allows to retrieve just the values associated with a particular attribute. Then, using the collection operators, you can quickly find the sum, count, min, max etc.
精彩评论