When adding 1 to NSUInteger result is multiples of 8

81 views Asked by At

I have a NSUInteger. In the viedDidLoad method I set it so 0 :

@property NSUInteger *unitOne;

//In viewdidload
_unitOne = 0;

This adds one to it. (This is in touchesBegan method. This code only takes place when a UIImageView is clicked. The UIImageView animates downwards in a loop.)

_unitOne++;
NSLog(@"%lu", (unsigned long) _unitOne);

When unitOne is supposed to equal 1, the debugger always says it's 8. When it need to equal 2, it is 16, and so on. Any ideas?

Note: If anyone needs more code, just tell me where you think it's going wrong and I'll add it.

1

There are 1 answers

0
Ken Thomases On BEST ANSWER

You have a pointer to an NSUInteger, not an NSUInteger as such. NSUInteger is a "primitive", "scalar" type, not an object type. You do not need to use pointers to them.

So, you created a pointer and set it to the null pointer value. 0 can always be assigned to a pointer variable and makes it the null pointer. So, you thought you were assigning an integer value to an integer variable but you weren't.

Then, you incremented the pointer. The semantics of C are that incrementing the pointer advances it to the "next" element of the pointed-to type. So, the pointer was incremented not by 1 byte but by the size of NSUInteger. When compiling 64-bit code, NSUInteger is 8 bytes in size. So, the pointer was incremented by 1 NSUInteger which is 8 bytes.

Then, when you logged the instance variable, you used a type cast to convert it to unsigned long. This fooled the compiler which would otherwise have warned about using %lu with a pointer parameter. The value of the pointer variable was logged, but it just pointed to 8 bytes up from the null pointer (0), and so on.