如何获得的NSNumber年代从NSArray的总和?(How get the total sum

2019-07-30 02:52发布

我有一个大NSArray含有NSNumbers3, 4, 20, 10, 1, 100,等...

我如何获得这些NSNumbers的总和(3 + 4 + 20 + 10 + 1 + 100 + etc...)作为一个总NSInteger

谢谢!

Answer 1:

NSInteger sum = 0;
for (NSNumber *num in myArray) {
  sum += [num intValue];
}


Answer 2:

您可以使用此:

NSArray* numbers = //array of numbers
NSNumber* sum = [numbers valueForKeyPath: @"@sum.self"];


Answer 3:

long long sum = ((NSNumber*)[array valueForKeyPath: @"@sum.longLongValue"]).longLongValue;


Answer 4:

通过阵列迭代

int count = [array count];
NSInteger sum = 0;
for (int i = 0; i < count; i++) {
    sum += [[array objectAtIndex:i] integerValue];
}


Answer 5:

[[numbersArray valueForKeyPath:@"@sum.self"] integerValue]


Answer 6:

int total = 0;
for (NSNumber *number in array)
{
  total += [number intValue];
}

可能这将帮助你



文章来源: How get the total sum of NSNumber's from a NSArray?