Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating a simple sum with Core Data

I have a simple Core Data store with an entity Cost with an integer property "value". I want to sum up all amounts of the costs in my store, which is equivalent to the following sql statement:

SELECT sum(value) FROM costs

How do I do it the most efficient way in Cocoa Touch? By using Core Data? Or just get all cost entities and do the summation manually?

like image 831
MrAlek Avatar asked Jul 31 '11 13:07

MrAlek


2 Answers

There are some special key value coding operators that work on arrays and sets, and one of them is @sum. If you fetch all the objects that you want to sum into a set called costs, and if the attribute that you want to sum for each object is value, you can then use the @sum operator like this:

float theSum = [costs valueForKeyPath:@"@sum.value"];
like image 150
Caleb Avatar answered Oct 25 '22 15:10

Caleb


The best way is to use a fetch for specific values and supply a NSExpressionDescription with a sum: function.

When you execute the fetch you get a one element array containing a dictionary whose keys match the expression descriptions and whose values are the results of the expressions. In this case, you would get a sum key whose value would be the sum of the attributes given the expression.

like image 31
TechZen Avatar answered Oct 25 '22 13:10

TechZen