Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

fstigre

macrumors regular
Original poster
Aug 12, 2008
158
1
Hi,

How can I add the numbers in an NSArray?

What I wan to do is add the numbers in an NSArray and log the result.

Here I'm printing the values of the NSArray but I don't know how to add them together.

Code:
        NSNumber *myInt;        
        myInt = [NSNumber numberWithInt:5];             
        
        NSNumber *myInt2;
        myInt2 = [NSNumber numberWithInt:10];
        
        NSArray *numbers =  [NSArray arrayWithObjects:myInt, myInt2, nil];
        
        for(int i = 0; i< [numbers count]; i++)
        {            
            NSLog(@"%@", [numbers objectAtIndex:i]);       

        }

Thanks
 
The posted code shows you already understand how to step through every item in the array. So make a loop that does that.

You already know each item in the array is an NSNumber object. So look at the class reference doc for NSNumber, and find a method that returns a value with a suitable numeric type, such as int, float, long, or double.

I assume you already know how to do arithmetic using variables with numeric types like int, float, long, or double. If not, you should study whatever you're learning from on how to use variables to perform arithmetic.

Given all the above, assemble the parts into a coherent whole: a loop that gets each item from the array, gets the numeric value from the NSNumber object, and performs arithmetic to add the numeric value to a sum.

Finally, look at the print format specifiers for NSLog (read the reference doc), to see how to print the numeric value of the sum.


Learning to program means learning how to break problems down into smaller pieces, solving each smaller piece, then building them into whole actions that provide the solution to the problem. This process (break it down, solve the pieces, build it up) is the essence of programming. The language it's written in is much less significant.
 
Thank you for your reply.

Ok, if I'm not mistaking what you are saying is that I basically need to convert the NSNumbers (objects) to primitive numbers such as int, float etc.

I will dig more into it.

Thanks a lot.
 
Last edited:
This is what I did.

Code:
NSNumber *myInt;
    myInt = [NSNumber numberWithInt:5];
    
    NSNumber *myInt2;
    myInt2 = [NSNumber numberWithInt:10];
    
    NSArray *numbers =  [NSArray arrayWithObjects:myInt, myInt2, nil];    
    
    int result =0;
    
    for(int i = 0; i < [numbers count]; i++)
    {        
        NSLog(@"Num: %@ \n", [numbers objectAtIndex:i]);
        result += [[numbers objectAtIndex:i] intValue];// getting the value of NSNumber 
    
    }    
    NSLog(@"Total: %i", result);
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.