2

Here is my code

I'm looping through the array and adding to the NSNumber.

NSNumber *totalValue = 0; 
NSMutableArray *items = [10, 35, 25]; // Just for demo
for (int i=0; i < items.count; i++)
{
    totalValue = totalValue + [items objectAtIndex:i] // How do I add the totalValue?
}

Can someone help me with this code?

3 Answers 3

9

NSNumber is an Objective-C class. Unlike in C++, operators cannot be overloaded in Objective-C so you have to call everything manually.

NSNumber *totalValue = [NSNumber numberWithInt:0];
for(…) {
  totalValue = [NSNumber numberWithInt:[totalValue intValue] + [[items objectAtIndex:i] intValue]];
}

You might want to use NSInteger instead, which is faster (especially for a large number of items: memory allocation is expensive):

NSInteger totalValueInteger = 0; // no pointer, NSInteger is a POD!
for (…) {
  totalValueInteger += [[items objectAtIndex:i] integerValue];
}
NSNumber *totalValue = [NSNumber numberWithInteger:totalValueInteger];

You should really only use NSNumber when you need an Objective-C object, like in an array, dictionary or coder. Otherwise, use a POD like NSInteger, int or double.

Sign up to request clarification or add additional context in comments.

Comments

1

First of all, you can probably do this entire thing using KVC:

NSNumber *total = [items valueForKeyPath:@"@sum.integerValue"];

But to answer your original question, NSNumber is immutable which means you can't change it or increment its value. Creating a new NSNumber on each iteration of your loop is inefficient and wasteful.

You should use a standard int or NSInteger to sum up the total, and then convert the resulting value to an NSNumber at the end if you need it like that.

2 Comments

I strongly suspect that this, while more succint/expressive, will be slower to execute.
Try it in Instruments. Then decide whether performance is important in this situation.
0

Might as well make the intermediate an int.

int temp = 0;
for(…) {
  temp += [[items objectAtIndex:i] intValue];
}
NSNumber *totalValue = [NSNumber numberWithInt:temp];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.