How to sum up a fetched result's number property based on the object's category?
Posted
by
mr_kurrupt
on Stack Overflow
See other posts from Stack Overflow
or by mr_kurrupt
Published on 2012-04-06T22:26:07Z
Indexed on
2012/04/06
23:29 UTC
Read the original article
Hit count: 230
I have a NSFetchRequest
that is returning all my saved objects (call them Item
s) and storing them in an NSMutableArray
. Each of these Item
s have a category, an amount, and some other properties. My goal is to check the category of each Item
and store the sum of the amounts for objects of the same category. So if I had these Item
s:
- Red; 10.00
- Blue; 20.00
- Green; 5.00
- Red; 5.00
- Green; 15.00
then I would have an array or other type of container than has:
- Red; 15.00
- Blue; 20.00
- Green; 20.00
What would be the best way to organize the data in such a manner? I was going to create a object class (call it Totals
) that just has the category and amount. As I traverse through the fetch results in a for-loop, add Item
s with the same category in a Totals
object an store them in a NSMutableArray
. The problem I ran into with that is that I'm not sure how to check if an array contains a Totals
object with a specific property. Specifically, a category that already exists. So if 'Red' exists, add the amount to it, otherwise create a new Totals
object with category 'Red' and a the first Item
's amount. Thanks.
© Stack Overflow or respective owner