NSInteger VS int

常能看到有人说苹果推荐大家使用NSInteger,就想知道为什么有此说法,今天研究了半下午,自己得出如下结论:

        1.苹果并没有说官方推荐使用NSInteger代替int.

2.平时使用时,如果跟API交互,通常根据API方法定义使用NSInteger,或者有某些特殊需求需要数据类型位宽和CPU架构一致时,使用NSInteger,其它表示普通数值时,也可以使用NSInteger,但如果对内存大小或者数值大小敏感的话,尽量使用short(int16_t)、 int(int32_t)、 long long(int64_t),这样比较明确数据范围。

       

        关于第一条,我在官方文档里没有搜到,而在别人转的文章里面,看到如下的一段文字,但也只是说如果你想让你的int尽可能的大时,使用NSInteger替代int,

You usually want to use NSInteger when you don't know what kind of processor architecture your code might run on, so you may for some reason want the largest possible int type, which on 32 bit systems is just an int, while on a 64-bit system it's a long.

 
  
  
 

有同事参加了开发者大会,说当时的演讲者说使用NSInteger的好处,是你在不同系统架构上编译代码,只需要声明NSInteger一种数据类型就可以了。可我的问题是,当你想传一个超过32位的数值给它时,该怎么办?

        关于为什么会出现NSInteger,很多人的解释也是上面一段文字,但我觉得理由太过牵强,在overflow里,我看到一条比较能让我信服的理由如下(尽管不是赞的最多的):

NSInteger and long are always pointer-sized. That means they're 32-bits on 32-bit systems, and 64 bits on 64-bit systems.

The reason NSInteger exists is because many legacy APIs incorrectly used int instead of long to hold pointer-sized variables, which meant that the APIs had to change from int to long in their 64-bit versions. In other words, an API would have different function signatures depending on whether you're compiling for 32-bit or 64-bit architectures. NSInteger intends to mask this problem with these legacy APIs.

In your new code, use int if you need a 32-bit variable, long long if you need a 64-bit integer, and long or NSInteger if you need a pointer-sized variable.

(http://stackoverflow.com/questions/4445173/when-to-use-nsinteger-vs-int)





猜你喜欢

转载自blog.csdn.net/dfqin/article/details/38823669
int