user6631314
user6631314

Reputation: 1960

IOS/Objective C/Core Data: Sum all the values for an attribute from query

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

Answers (1)

Kunal Shah
Kunal Shah

Reputation: 1121

You can use key-value coding:

NSNumber *orderTotal = [arrayWhoseSumIsToBeCalculated valueForKeyPath:@"@sum.self"];

Upvotes: 1

Related Questions