开发者

How to add array values using NSMutableArray in iPHone?

I have the data into the mutable array and the value of array is,

     { "20", "40开发者_StackOverflow", "50","60", "70"}.

I have stored the string values into the array.

Now i want to total value of the array. Result is : 240

Thanks!


NSInteger value = 0;
for (String *digit in myArray) {
    value += [digit intValue];
}


int total=0;
for(NSString *currentString in myArray){
     total +=[currentString intValue]; 
}
NSLog(@"Sum:%d",total);


This adds all values:

__block NSInteger sum = 0;
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    sum += [obj intValue];
}];


You can do as follows:

int totalSum = 0;
NSmutableArray *arrayData = [[NSmutableArray alloc] init];
[arrayData addObject:@"20"];
[arrayData addObject:@"40"];
[arrayData addObject:@"50"];
[arrayData addObject:@"60"];
[arrayData addObject:@"70"];

for(int i=0; i<[arrayData count];i++)
{
     totalSum = totalSum + [[arrayData objectAtIndex:i] intValue];
}

NSLog(@"Total:%d",totalSum);

Please let me know if you have any question.


How about the most elegant solution using key-value Collection aggregators:

NSNumber *sum = [myArray valueForKeyPath:@"@sum.self"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜