在索引处添加NSMutableArray的元素以及其他NSMutableArrays的相应元素

时间:2012-08-10 22:05:21

标签: ios objective-c arrays xcode

如果我有3个NSMutableArray,我怎样才能得到一个数组,其中每个索引处的元素是每个原始数组中相同索引处元素的总和?

示例:

MutableArrayOne  = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

MutableArrayTwo  = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

MutableArrayThree  = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

如何将它们总结为如下数组:

MutableArrayThree  = [NSMutableArray arrayWithObjects:@"3",@"6",@"9",@"12",@"15", nil];

1 个答案:

答案 0 :(得分:3)

假设所有阵列都具有相同的大小......

NSMutableArray *sums = [NSMutableArray arrayWithCapacity:MutableArrayOne.count];
for(NSInteger i = 0; i < MutableArrayOne.count; i++)
{
    NSInteger element1 = [[MutableArrayOne objectAtIndex:i] integerValue];
    NSInteger element2 = [[MutableArrayTwo objectAtIndex:i] integerValue];
    NSInteger element3 = [[MutableArrayThree objectAtIndex:i] integerValue];
    NSInteger sum = element1 + element2 + element3;
    [sums addObject:[NSString stringWithFormat:@"%lu", sum]];
}