views:

237

answers:

3

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.

+3  A: 

I 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.

Jonathan Sterling
Isn't "int" supposed to be the right size anyway? Unless "right" means something different based on context, e.g. right size for the processor vs. right size for the libraries.
squelart
Mac OS X, along with most versions of Unix, uses LP64. In LP64, longs, and pointers are 64 bits, and ints are 32 bits.http://www.unix.org/version2/whatsnew/lp64_wp.html
Jon Hess
+3  A: 

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.

Dave DeLong
+2  A: 
  • 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 or NSInteger
  • 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.

Darren
I’d say, if you need a 4-byte integer, use `int32_t` (and, of course, `int64_t` for 8-byte). This way you express clearly the size and don’t depend on the platform/architecture.
Nikolai Ruhe
+1, nevertheless, for the best answer.
Nikolai Ruhe