2012-08-10 3 views
0

NSMutableArray가 3 개이면 각 인덱스의 요소가 원래 배열의 같은 인덱스에있는 요소의 합계 인 배열을 어떻게 얻을 수 있습니까?다른 NSMutableArrays의 해당 요소를 인덱스에 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

내가 물어 봐도 될까요 왜 그것은 가변 배열입니까? – Joe

+0

왜냐하면 그 전에는 NSMutableArray를 사용해야하는 다른 코딩이 있기 때문입니다. – Lollo

+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]]; 
} 
+0

['NSInteger'는 long 형으로 캐스트되어야합니다] (https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html),'% lu '지정자 맞다. – Joe

관련 문제