How get the total sum of NSNumber's from a NSArray?
Asked Answered
A

6

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!

Affiance answered 25/6, 2012 at 15:37 Comment(0)
F
159

You can use this:

NSArray* numbers = //array of numbers
NSNumber* sum = [numbers valueForKeyPath: @"@sum.self"];
Feral answered 25/6, 2012 at 15:46 Comment(5)
This is the most elegant solution. Docs here:developer.apple.com/library/ios/ipad/#documentation/cocoa/…Rubeola
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.Ats
Also it's documented to do all arithmetic with doubles. 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.Inulin
Does anyone know how to perform those @sum.self in Swift?Retroact
This also suffers from poor performance if the array has 1000s of numbers. Better to use fast-enumeration insteadIntercontinental
P
20
NSInteger sum = 0;
for (NSNumber *num in myArray) {
  sum += [num intValue];
}
Poulter answered 25/6, 2012 at 15:41 Comment(0)
B
9
long long sum = ((NSNumber*)[array valueForKeyPath: @"@sum.longLongValue"]).longLongValue;
Barrington answered 25/6, 2012 at 15:41 Comment(1)
valueForKeyPath: returns an object, not an integer.Leftwich
C
4

Iterate through the array

int count = [array count];
NSInteger sum = 0;
for (int i = 0; i < count; i++) {
    sum += [[array objectAtIndex:i] integerValue];
}
Counterintelligence answered 25/6, 2012 at 15:40 Comment(0)
E
3
[[numbersArray valueForKeyPath:@"@sum.self"] integerValue]
Explicative answered 25/6, 2012 at 16:50 Comment(0)
S
2
int total = 0;
for (NSNumber *number in array)
{
  total += [number intValue];
}

may this will help you

Shamefaced answered 25/6, 2012 at 15:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.