What is the advantage of using something like NSInteger
instead of int
in code? I see this in examples a lot, including Apple's official code samples.
views:
237answers:
3I am pretty sure that NSInteger
and NSUInteger
were invented to solve 64-bit quantization issues on Mac OS (they are guaranteed to be the right size, no matter what architecture you are building for). I don't think it matters what you use on the iPhone, though I would get in the habit of using Apple's NS
-types.
Anyway, if you ever port your code to Mac OS, it will be easier.
There's a similar question here on SO.com: http://stackoverflow.com/questions/13725 I prefer using NSInteger
because it's future-proof, Apple now uses it over int
, and it's the recommended way of doing things.
But it's not "wrong" to use int
.
- In 32-bit code (including the iPhone):
int
is 4 bytes,long
is 4 bytes, pointers are 4 bytes - In 64-bit code:
int
is 4 bytes,long
is 8 bytes, pointers are 8 bytes
Many existing APIs (incorrectly, for historical reasons) used int
in 32-bit mode but must use long
in 64-bit mode.
In C, int
and long
are not equivalent types, so if you use int
you may be incompatible with the 64-bit API, and if you use long
you may be incompatible with the 32-bit API. By using NSInteger
your code will be compatible with both 32-bit and 64-bit versions of these APIs.
So if you're using an API that specifies NSInteger, then you should use NSInteger.
In your own code and your own APIs:
- If you need a 4-byte integer, use
int
- If you need a pointer-sized integer, use
long
orNSInteger
- if you need an 8-byte integer, use
long long
The reason you wouldn't necessarily use NSInteger for everything is that 8-byte integers are overkill for many purposes.