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:
then I would have an array or other type of container than has:
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.
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.