Difference between int, NSInteger and NSUInteger

纵然是瞬间 提交于 2019-11-29 10:38:00

问题


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

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


回答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



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



来源:https://stackoverflow.com/questions/7626412/difference-between-int-nsinteger-and-nsuinteger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!