Obj-C - 获取键中所有值的总和?
Obj-C - Get the sum of all values in a key?
我正在寻找我的 NSDictionary (self.itemDetails) 中键 'cost' 中所有值(数字)的总和。
NSNumber *sum = [self.itemDetails valueForKey:@"@sum.cost"];
就是说,上面一行导致我的应用程序崩溃并显示以下内容。
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
我做错了什么?
编辑:
这可能会澄清一些事情。 self.itemDetails (NSDictionary) 被添加到 NSMutableArray (self.allItems)。这是我返回的字典数组的结构。我正在尝试计算所有 'cost' 键的总和:
[55155:2221932] All of the items in here (
{
cost = 30;
description = Test;
name = Test;
rate = 5;
},
{
cost = 50;
description = Test;
name = Test;
rate = 5;
}
)
遍历所有字典并添加成本。像这样:
NSInteger totalCosts = 0;
for (item in self.allItems) {
totalCosts += [item[@"cost"] integerValue];
}
这就是最终对我有用的东西:
NSNumber *sum = [self.allItems valueForKey:@"@sum.cost"];
我正在寻找我的 NSDictionary (self.itemDetails) 中键 'cost' 中所有值(数字)的总和。
NSNumber *sum = [self.itemDetails valueForKey:@"@sum.cost"];
就是说,上面一行导致我的应用程序崩溃并显示以下内容。
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
我做错了什么?
编辑:
这可能会澄清一些事情。 self.itemDetails (NSDictionary) 被添加到 NSMutableArray (self.allItems)。这是我返回的字典数组的结构。我正在尝试计算所有 'cost' 键的总和:
[55155:2221932] All of the items in here (
{
cost = 30;
description = Test;
name = Test;
rate = 5;
},
{
cost = 50;
description = Test;
name = Test;
rate = 5;
}
)
遍历所有字典并添加成本。像这样:
NSInteger totalCosts = 0;
for (item in self.allItems) {
totalCosts += [item[@"cost"] integerValue];
}
这就是最终对我有用的东西:
NSNumber *sum = [self.allItems valueForKey:@"@sum.cost"];