Difference between int, NSInteger and NSUInteger

前端 未结 2 1183
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 19:27

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

Which one is better to use in an applicatio

相关标签:
2条回答
  • 2020-12-30 20:02

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

    0 讨论(0)
  • 2020-12-30 20:13

    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
    
    0 讨论(0)
提交回复
热议问题