How do I get the total sum of all entries in a Core Data attribute?


I've got a Core Data Data Model with an Entity and several Attributes.

One of these Attributes is an Integer 16 (NSDecimalNumber) called


I want to find the sum of all the entries I have in my data model from this Attribute.

In other words: I'll have many user entries in this Attribute. Lets say the user creates 3 entries with these specifics:

1) numberOfSeconds = 4

2) numberOfSeconds = 2

3) numberOfSeconds = 5

I'm hoping to be able to grab the total sum which should equal 11.

Appreciate any help in this!

You can use NSExpressionDescription to get the sum directly via fetch request (without fetching the managed objects themselves, which can be inefficient if you have many of them).

Remember to set NSDictionaryResultType for the fetch request (I got EXC_BAD_ACCESS if I didn't do that).

NSExpression *keyExpression = [NSExpression expressionForKeyPath:@"numberOfSeconds"];
NSExpression *sumExpression = [NSExpression expressionForFunction:@"sum:" arguments:@[keyExpression]];

NSExpressionDescription *sumDescription = [[NSExpressionDescription alloc] init]; = @"sumOfSeconds";
sumDescription.expression = sumExpression;
[sumDescription setExpressionResultType:NSDecimalAttributeType];

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Entity"];
request.resultType = NSDictionaryResultType;
[request setPropertiesToFetch:@[sumDescription]];

NSError *error = nil;
NSManagedObjectContext *context = ... //get the context somehow
NSArray* fetchResult = [context executeFetchRequest:request error:&error];
NSNumber *sum = fetchResult.firstObject[];  //this is your sum

Reference: Apple Core Data guide