36

What is the main difference between int, NSInteger and NSUInteger in Objective-C?

Which one is better to use in an application and why?

viral
  • 4,168
  • 5
  • 43
  • 68
Hitarth
  • 1,950
  • 3
  • 27
  • 52
  • There's no such thing as `NSInt`. – BoltClock Oct 02 '11 at 12:48
  • 2
    [See the documentation](http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html) – Jiri Oct 02 '11 at 12:59

2 Answers2

29

In such cases you might right click and go to definition:

#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
Bastian
  • 10,403
  • 1
  • 31
  • 40
20

The difference is for abstract types and their associates sized from hardware. In a manner that now we don't have to worry about what size an int is or how big it's pointer is on any particular hardware.

"C" is bad at this, only stating that a long is at least as big as an int, that an int is the "natural" integer size of the hardware (whatever that means), that an int is at least as long as a short--a (big mess).

This seemed like a good idea at the time coming from Fortran, but did not age well.

One could use the POSIX defines, things like uint32_t, int16_t, etc. But this does not address how big a pointer needs to be on any particular hardware either.

So, if Apple defines the return type to be an NSUInteger you just use that and you don't need to know if it is 16, 32 or 64 bits in size for your particular hardware. (I picked those values out-of-the-air just for an example).

As you can see in @Bastian the actual size depends on hardware.

The documentation answers the "letter of the question" but does not provide an understanding of "why"?

INSITE MOBILE
  • 133
  • 1
  • 10
zaph
  • 111,848
  • 21
  • 189
  • 228
  • you r right .we get only the difference between them but why ? i m still not getting please suggest me – Hitarth Oct 02 '11 at 13:40
  • 3
    It's API standardization. These frameworks ship on multiple architectures -- it's nice for API to be the same across them all. By having these typedefs, Apple is abstracting platform differences away from API consumers. If you only speak to the API in terms of these types, then (in theory) you don't need to think about platform differences when compiling the same code for i386, x86_64, ppc, arm7, or whatever. It's an abstraction. It's been said that you should use the highest level of abstraction that gets the job done. So unless you have a reason NOT to use these types, I say use 'em. – ipmcc Oct 02 '11 at 14:34