Difference between int, NSInteger and NSUInteger

21,674

Solution 1

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

Solution 2

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"?

Share:
21,674
Hitarth
Author by

Hitarth

Updated on August 21, 2020

Comments

  • Hitarth
    Hitarth over 3 years

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

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

  • Hitarth
    Hitarth over 12 years
    you r right .we get only the difference between them but why ? i m still not getting please suggest me
  • ipmcc
    ipmcc over 12 years
    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.