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)





 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值