3

I have a NSArray containing a list of NSDictionary. Like:

NSArray *array = ...;
NSDictionary *item = [array objectAtIndex:0];
NSLog (@"quantity: %@", [item objectForKey: @"quantity"]);

How can I sum all the quantities contained in all dictionaries of the array?

Janak Nirmal
  • 22,706
  • 18
  • 63
  • 99
lolol
  • 4,287
  • 3
  • 35
  • 54

3 Answers3

8

I think you can try KVC

NSMutableArray *goods = [[NSMutableArray alloc] init];
NSString *key = @"quantity";

[goods addObject:@{key:@(1)}];

[goods addObject:@{key:@(2)}];

[goods addObject:@{key:@(3)}];

NSNumber *sum = [goods valueForKeyPath:@"@sum.quantity"];
NSLog(@"sum = %@", sum);
sunkehappy
  • 8,970
  • 5
  • 44
  • 65
  • You're updating the same dictionary and adding it 3 times, so the sum will be 9, when you'd expect 6. You need to create a new dictionary in each case, like `[goods addObject:@{@"quantity": @1}];` – Christopher Pickslay Aug 01 '13 at 07:17
2

If you call valueForKey: on an array it gives you an array of all the values for that key, so [array valueForKey:@"quantity"] will give you an array which you can loop over and sum all the values.

rdelmar
  • 103,982
  • 12
  • 207
  • 218
0
NSMutableArray *quantityArray = [item objectForKey: @"quantity"];
int total =0;
for(int i=0;i<[quantityArray count];i++)
{
  total+= [quantityArray objectAtIndex:i];
}
Durga Vundavalli
  • 1,790
  • 22
  • 26