Discussion in 'iOS Programming' started by fstigre, Nov 10, 2012.

1. fstigre macrumors regular

Joined:
Aug 12, 2008
#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

2. chown33 macrumors 604

Joined:
Aug 9, 2009
Location:
Brobdingnag
#2
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.

3. Nov 10, 2012
Last edited: Nov 11, 2012

Joined:
Aug 12, 2008
#3

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.

4. fstigre thread starter macrumors regular

Joined:
Aug 12, 2008
#4
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);```

Joined:
Aug 9, 2009
Location:
Brobdingnag