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!
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!
You can use this:
NSArray* numbers = //array of numbers
NSNumber* sum = [numbers valueForKeyPath: @"@sum.self"];
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. –
Inulin @sum.self
in Swift? –
Retroact NSInteger sum = 0;
for (NSNumber *num in myArray) {
sum += [num intValue];
}
long long sum = ((NSNumber*)[array valueForKeyPath: @"@sum.longLongValue"]).longLongValue;
valueForKeyPath:
returns an object, not an integer. –
Leftwich Iterate through the array
int count = [array count];
NSInteger sum = 0;
for (int i = 0; i < count; i++) {
sum += [[array objectAtIndex:i] integerValue];
}
[[numbersArray valueForKeyPath:@"@sum.self"] integerValue]
int total = 0;
for (NSNumber *number in array)
{
total += [number intValue];
}
may this will help you
© 2022 - 2024 — McMap. All rights reserved.