iOS 基础篇(一): char、int、long、NSInteger类型对比

1. 表格

类型 32位系统位宽 64位系统位宽 32位系统范围(十进制) 64位系统范围(十进制) 是否平台自适应 推荐使用场景
char 1字节 1字节 -128 ~ 127 (-2^7 ~ 2^7 - 1) -128 ~ 127 (-2^7 ~ 2^7 - 1) ❌ 固定大小 ASCII字符/小整数
signed char 1字节 1字节 -128 ~ 127 (-2^7 ~ 2^7 - 1) -128 ~ 127 (-2^7 ~ 2^7 - 1) ❌ 固定大小 明确有符号的小整数
unsigned char 1字节 1字节 0 ~ 255 (0 ~ 2^8 - 1) 0 ~ 255 (0 ~ 2^8 - 1) ❌ 固定大小 字节数据/无符号小整数
int 4字节 4字节 -2147483648 ~ 2147483647 (-2^31 ~ 2^31 - 1) 同32位系统范围 ❌ 固定大小 跨平台开发/C语言交互
long 4字节 8字节 -2147483648 ~ 2147483647 (-2^31 ~ 2^31 - 1) -9223372036854775808 ~ 9223372036854775807 (-2^63 ~ 2^63 - 1) ❌ 需手动处理 需要极大整数的场景
NSInteger 4字节 8字节 -2147483648 ~ 2147483647 (-2^31 ~ 2^31 - 1) -9223372036854775808 ~ 9223372036854775807 (-2^63 ~ 2^63 - 1) ✅ 自动适配 Cocoa API/iOS/macOS应用开发
NSUInteger 4字节 8字节 0 ~ 4294967295 (0 ~ 2^32 - 1) 0 ~ 18446744073709551615 (0 ~ 2^64 - 1) ✅ 自动适配 Cocoa API中的无符号整数

2. NSInteger / NSUInteger 源码 (编译时自动切换定义)

objectivec 复制代码
#if __LP64__ || NS_BUILD_32_LIKE_64
    typedef long NSInteger;
    typedef unsigned long NSUInteger;
#else
    typedef int NSInteger;
    typedef unsigned int NSUInteger;
#endif

3. NSInteger 类型可以提高可移植性的原因

在 Objective-C 开发中,优先使用 NSInteger 替代 intlong,以提高代码的可移植性。原因如下:

  1. 自动平台适配
    • 在32位系统上,NSInteger 被定义为 int(4字节)
    • 在64位系统上,NSInteger 被定义为 long(8字节)
    • 开发者无需编写条件编译代码即可适应不同架构。
  2. 数据完整性保障 :
    • 在64位系统上,当整数值超过32位范围(>2,147,483,647)时,使用 int 会导致数据截断。NSInteger 在64位下使用64位存储,可安全处理大整数,避免数据丢失。
  3. 无缝API集成与代码简化
    • API兼容性 :Cocoa/Cocoa Touch框架的方法参数和返回值(如数组的count、索引值)广泛使用NSInteger,直接使用该类型无需类型转换。
    • 减少条件编译:消除针对32/64位系统的条件判断代码,使代码更简洁。
    • 未来兼容 :若Apple引入新架构(如128位),只需调整NSInteger的底层定义,现有代码无需修改。
相关推荐
初级代码游戏10 小时前
easy Photo Clean公测版:快速清理iPhone照片 邀请公测
ios·iphone
库奇噜啦呼10 小时前
【iOS】RunLoop学习
学习·ios
黑科技iOS上架12 小时前
iOS应用周末提交什么情况算卡审
经验分享·ios
zzb158014 小时前
ios基础-MVC-UIView
ios·mvc·cocoa
kingbal14 小时前
Flutter:Flutter SDK版本管理工具FVM
android·flutter·ios·android-studio·window
他们都不看好你,偏偏你最不争气1 天前
【iOS】Runtime - Part 2 && 消息发送:缓存、查找与转发
macos·ios·objective-c·cocoa
2501_915918411 天前
iOS App性能测试工具的实现方法与优化循环指南
android·ios·小程序·https·uni-app·iphone·webview
他们都不看好你,偏偏你最不争气1 天前
【iOS】Runtime - Part 1 && 对象与类的本质
macos·ios·objective-c·cocoa