Dan Carlson
Dan Carlson

Reputation: 971

NSNumber LoopVar++ in for loop increments by 4 instead of by 1

I'm quite sure that this question has a very simple answer that I should have figured out by now. Since I haven't yet done so I come to you, stack overflow hive mind.

I expected the loop below to print out the numbers from 0 to 5. Instead it prints out only 0 and 4. Why does LoopNumber++ increment my NSNumber LoopNumber by 4 instead of by 1?

NSNumber *LoopNumber;
for (LoopNumber=0; LoopNumber<=5; LoopNumber++) {
    NSLog(@"%d",LoopNumber);
}

If I change it to the following it works exactly as I expect. What gives?

for (int LoopNumber=0; LoopNumber<=5; LoopNumber++) {

I'm fooling around with an iPhone project in XCode 3.2.1, using SDK 3.1.2.

Upvotes: 0

Views: 2109

Answers (2)

Brad The App Guy
Brad The App Guy

Reputation: 16275

an NSNumber is not an integer. It is an object wrapper for a number which may be an integer.

The variable LoopNumber is actually a pointer to the location in memory where the object should be. All LoopNumber itself holds is a memory address, which on your machine is 4 bytes long. When you do LoopNumber++ you are inzoking pointer aritmatic on the pointer and it is advancing to the next memory address which is four bytes later. You can see this by doing a sizeof(LoopNumber) - that would return 4 on your system.

What you really want to do is use a regular integer like so:

NSUInteger loopNumber;
for(loopNumber = 0; loopNumber <= 5; loopNumber++) {
  NSLog(@"%d",loopnumber);
}

or if you really need to use NSNumbers:

NSNumber loopNumber;
for(loopNumber = [NSNumber numberWithInt:0]; [loopNumber intValue] <= 5; loopNumber=[NSNumber numberWithInt:[loopNumber intValue]++]) {
  NSLog(@"%d",loopnumber);
}

Upvotes: 4

Swapna
Swapna

Reputation: 2235

int is native type. NSNumber is a Objective-C class. Use float or int when doing real work. But to put a int into a collection you can create an NSNumber object from the int or float native type.

Upvotes: 0

Related Questions