Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 512
neowinston Avatar asked Jun 25 '12 15:06

neowinston


3 Answers

You can use this:

NSArray* numbers = //array of numbers
NSNumber* sum = [numbers valueForKeyPath: @"@sum.self"];
like image 135
Paul de Lange Avatar answered Oct 17 '22 08:10

Paul de Lange


NSInteger sum = 0;
for (NSNumber *num in myArray) {
  sum += [num intValue];
}
like image 36
Alladinian Avatar answered Oct 17 '22 08:10

Alladinian


long long sum = ((NSNumber*)[array valueForKeyPath: @"@sum.longLongValue"]).longLongValue;
like image 9
fabrice truillot de chambrier Avatar answered Oct 17 '22 08:10

fabrice truillot de chambrier