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?
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"];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With