26

我有一个大NSArray的包含之NSNumbers类的3, 4, 20, 10, 1, 100,......

如何将所有这些 NSNumbers 的总和(3 + 4 + 20 + 10 + 1 + 100 + etc...)作为一个总数NSInteger

谢谢!

4

6 回答 6

158

你可以使用这个:

NSArray* numbers = //array of numbers
NSNumber* sum = [numbers valueForKeyPath: @"@sum.self"];
于 2012-06-25T15:46:25.043 回答
20
NSInteger sum = 0;
for (NSNumber *num in myArray) {
  sum += [num intValue];
}
于 2012-06-25T15:41:02.593 回答
9
long long sum = ((NSNumber*)[array valueForKeyPath: @"@sum.longLongValue"]).longLongValue;
于 2012-06-25T15:41:48.230 回答
4

遍历数组

int count = [array count];
NSInteger sum = 0;
for (int i = 0; i < count; i++) {
    sum += [[array objectAtIndex:i] integerValue];
}
于 2012-06-25T15:40:24.063 回答
3
[[numbersArray valueForKeyPath:@"@sum.self"] integerValue]
于 2012-06-25T16:50:06.757 回答
2
int total = 0;
for (NSNumber *number in array)
{
  total += [number intValue];
}

这可能会帮助你

于 2012-06-25T15:42:38.273 回答