2012-06-25 6 views

Respuesta

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

iterar a través de la matriz

int count = [array count]; 
NSInteger sum = 0; 
for (int i = 0; i < count; i++) { 
    sum += [[array objectAtIndex:i] integerValue]; 
} 
7
long long sum = ((NSNumber*)[array valueForKeyPath: @"@sum.longLongValue"]).longLongValue; 
+0

¡Muchas gracias! – Winston

+0

'valueForKeyPath:' devuelve un objeto, no un número entero. –

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

puede esto le ayudará a

148

Puede utilizar esta:

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

Esta es la solución más elegante. Documentos aquí: http: //developer.apple.com/library/ios/ipad/#documentation/cocoa/conceptual/KeyValueCoding/Articles/CollectionOperators.html – Jon

+1

Esta es definitivamente la solución más elegante. Sin embargo, hay un pequeño problema. Si uno de los elementos en la matriz es NSNull, se bloquea. –

+0

También está documentado hacer toda la aritmética con 'double's. Entonces, cinco años después, con el tiempo de ejecución de 64 bits y el 'NSInteger' siendo ahora del mismo tamaño que un' doble', eso corre el riesgo de pérdida de precisión cuando los números son grandes. – Tommy

3
[[numbersArray valueForKeyPath:@"@sum.self"] integerValue] 
Cuestiones relacionadas