我有一个数组宽度这个值:
array: (
{
id = 1;
name = "Cursus Nibh Venenatis";
value = "875.24";
},
{
id = 2;
name = "Elit Fusce";
value = "254.02";
},
{
id = 3;
name = "Bibendum Ornare";
value = "123.42";
},
{
id = 4;
name = "Lorme Ipsim";
value = "586.24";
}
)
我需要做的是获取每个'价值'并将其全部加起来。我宣布一个新的数组来取每个值:
self.valuesArray = [[NSArray alloc] init];
但是我该怎么办呢?谢谢你的回答!
答案 0 :(得分:4)
double sum = [[array valueForKeyPath:@"@sum.value"] doubleValue];
您可以阅读有关集合运算符here
的更多信息答案 1 :(得分:1)
你已经声明了数组,所以我将使用你的。我还假设您的第一个数组(包含上面的数据集)是一个名为myFirstArray
的数组(类型为NSArray)
int sum =0;
self.valuesArray = [[NSMutableArray alloc] init];
for(NSDictionary *obj in myFirstArray){
NSString *value =[obj objectForKey:@"value"];
sum+= [value intValue];
[self.valuesArray arrayWithObject:value];//this line creates a new NSArray instance which conains array of 'values'(from your dictionary)
}
NSLog("The sum of values is: %d", sum);
NSLog("The array of \'values\' is : %@",self.valuesArray );
答案 2 :(得分:0)
double sum=0.0;
for (YourDataObject *d in array) {
sum+=[[d getValue] doubleValue];
}
答案 3 :(得分:0)
试试这个 -
float totalValue = 0.0f;
for (int i = 0 ; i< [array count]; i++) {
totalValue +=[[[array objectAtIndex:i] objectForKey:@"value"] floatValue];
}