Reputation: 5088
I have one array that is pre-filled with dictionaries with each dictionary consisting of two keys.
{
name = object1;
quantity = 5;
},
{
name = object2;
quantity = 2;
}
I want to be able to add more objects and combine any duplicate dictionaries. So for example, if I added 5 of object one and 3 of object 2, this would be the result.
{
name = object1;
quantity = 10;
},
{
name = object2;
quantity = 5;
}
My ultimate goal is to be able to display the quantity next to the item in a table view. What is the best way to accomplish this?
Upvotes: 1
Views: 159
Reputation: 2992
If you really want to iterate through your existing structure then you could do something like:
for (NSMutableDictionary *dict in ArrayName) {
if([[dict valueForKey:@"name"] isEqual:someobject]) {
int oldValue = [[dict valueForKey:@"quantity"] intValue];
[dict setValue:[NSString stringWithFormat:@"%d",oldValue+1] forKey:@"quantity"];
}
}
I assumed you stored the quantity as an NSString, you may have used something else like NSNumber.
I think a better idea is create your own class with two properties, a name and a quantity. Then hold one array of those objects and iterate through that.
Upvotes: 1
Reputation: 31
I do not have a clear idea of what you are exacly doing but,
you may solve this problem with just a dictionary (without an array) that stores you objects as its key and their count as its value.
so when you want to add an object, you first check to see if you alerady have that object -if you dont have it you add object1=1 -if you have it then you increment the value of that object1=2
Upvotes: 0
Reputation: 1246
Well since the keys for your dictionaries always look the same, I'd wonder if that's not actually a different dictionary:
{ object1: 10, object2: 5}
Assuming your object names are valid keys, I'd use those as keys, and then just increment the counters as needed when you get more objects to add.
Upvotes: 0