0

我有一个数组宽度这个值:

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];

但是我该怎么做呢?感谢您的回答!

4

4 回答 4

4
double sum = [[array valueForKeyPath:@"@sum.value"] doubleValue];

您可以在此处阅读有关集合运算符的更多信息

于 2012-08-01T12:30:40.687 回答
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 );
于 2012-08-01T12:31:39.603 回答
0
double sum=0.0;

for (YourDataObject *d in array) {
    sum+=[[d getValue] doubleValue];
}
于 2012-08-01T12:24:31.777 回答
0

尝试这个 -

 float totalValue = 0.0f;

 for (int i = 0 ; i< [array count]; i++) {
     totalValue +=[[[array objectAtIndex:i] objectForKey:@"value"] floatValue];
}
于 2012-08-01T12:26:42.347 回答