Reputation: 1449
I'm looking to get the sum of all values (numbers) in key 'cost' in my NSDictionary (self.itemDetails).
NSNumber *sum = [self.itemDetails valueForKey:@"@sum.cost"];
That said, the above line causes my app to crash with the following.
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSDictionaryM 0x281ab4e20> valueForUndefinedKey:]: this class is not key value coding-compliant for the key sum.Item Cost.' terminating with uncaught exception of type NSException
What am I doing wrong here?
Edit:
This might clarify things. self.itemDetails (NSDictionary) is being added to an NSMutableArray (self.allItems). Here's the structure of my returned array of dictionaries. I'm trying to calculate the sum of all 'cost' keys:
[55155:2221932] All of the items in here (
{
cost = 30;
description = Test;
name = Test;
rate = 5;
},
{
cost = 50;
description = Test;
name = Test;
rate = 5;
}
)
Upvotes: 2
Views: 230
Reputation: 1449
This is what ended up working for me:
NSNumber *sum = [self.allItems valueForKey:@"@sum.cost"];
Upvotes: 2
Reputation: 14073
Iterate over all dictionaries and add the costs. Like this:
NSInteger totalCosts = 0;
for (item in self.allItems) {
totalCosts += [item[@"cost"] integerValue];
}
Upvotes: -1