Reputation: 1960
I would like to add up all the values of a certain attribute following a fetch from core data. Is there some shortcut such as sum that would quickly return this.
Here is my standard code for a fetch. Looking for something that would total up the values of orderprice to get the sum of all orders
- (id) getSalesTotal{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Orders"];
fetchRequest.resultType = NSDictionaryResultType;
NSError *error = nil;
self.managedObjectContext = [IDModel sharedInstance].managedObjectContext;
NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest
error:&error];
NSLog(@"error is %@",error);
// NSLog(@"context%@",results);
NSLog(@"beforevalueforkey%@",results);
NSMutableArray * ordertotal = [[results valueForKey:@"orderprice"] mutableCopy];
return ordertotal;//Is there something like sum(ordertotal)?????
}
Upvotes: 0
Views: 93
Reputation: 1121
You can use key-value coding:
NSNumber *orderTotal = [arrayWhoseSumIsToBeCalculated valueForKeyPath:@"@sum.self"];
Upvotes: 1