Search code examples
iphoneiosnsmutablearraynsfetchedresultscontrollernsfetchrequest

How to sum up a fetched result's number property based on the object's category?


I have a NSFetchRequest that is returning all my saved objects (call them Items) and storing them in an NSMutableArray. Each of these Items 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 Items:

  • 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 Items 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.


Solution

  • To answer your question and to give you generic methods that can prove helpful in many situations, you can use the [myObject isKindOfClass:aClass] method, then the respondsToSelector: method of NSObject.

    If you know what are the kind of data you're gonna get.. You can just instantiate an object Totals with Red = 0, Blue = 0, Green = 0, then add amounts accordingly.

    As an other option, you can take a look at Key-value coding : link here

    you can use the NSMutableDictionary class to achieve that. You will look in your total object (NSMutableDictionary) if key exists, if not, create it, if yes add value.