26

I have a large NSArray containing NSNumbers like 3, 4, 20, 10, 1, 100, etc...

How do I get the total sum of all these NSNumbers (3 + 4 + 20 + 10 + 1 + 100 + etc...) as one total NSInteger?

Thank you!

neowinston
  • 7,584
  • 10
  • 52
  • 83

6 Answers6

159

You can use this:

NSArray* numbers = //array of numbers
NSNumber* sum = [numbers valueForKeyPath: @"@sum.self"];
Paul de Lange
  • 10,613
  • 10
  • 41
  • 56
  • 5
    This is the most elegant solution. Docs here:http://developer.apple.com/library/ios/ipad/#documentation/cocoa/conceptual/KeyValueCoding/Articles/CollectionOperators.html – Jon Mar 18 '13 at 17:22
  • 1
    This is definitely the most elegant solution. However there's a small problem. If one of the elements in the array is NSNull, it crashes. – Sumit Nathany Feb 12 '15 at 10:35
  • Also it's documented to do all arithmetic with `double`s. So, five years later, with the 64-bit runtime and `NSInteger` now being the same size as a `double`, that risks loss of precision when numbers are large. – Tommy Feb 24 '17 at 14:58
  • 1
    Does anyone know how to perform those `@sum.self` in Swift? – Eddie Mar 29 '18 at 07:57
  • This also suffers from poor performance if the array has 1000s of numbers. Better to use fast-enumeration instead – Z S Jun 14 '21 at 18:06
20
NSInteger sum = 0;
for (NSNumber *num in myArray) {
  sum += [num intValue];
}
Alladinian
  • 34,483
  • 6
  • 89
  • 91
9
long long sum = ((NSNumber*)[array valueForKeyPath: @"@sum.longLongValue"]).longLongValue;
Rahul Patel
  • 5,858
  • 6
  • 46
  • 72
4

Iterate through the array

int count = [array count];
NSInteger sum = 0;
for (int i = 0; i < count; i++) {
    sum += [[array objectAtIndex:i] integerValue];
}
Alexander
  • 8,117
  • 1
  • 35
  • 46
3
[[numbersArray valueForKeyPath:@"@sum.self"] integerValue]
diederikh
  • 25,221
  • 5
  • 36
  • 49
2
int total = 0;
for (NSNumber *number in array)
{
  total += [number intValue];
}

may this will help you

Abhishek
  • 2,255
  • 1
  • 13
  • 21