为什么 NSInteger 变量在用作格式参数时必须强制转换为 long? [英] Why does an NSInteger variable have to be cast to long when used as a format argument?
问题描述
NSInteger myInt = 1804809223;
NSLog(@"%i", myInt); <====
上面的代码产生了一个错误:
The code above produces an error:
'NSInteger' 类型的值不应用作格式参数;改为向long"添加显式转换
Values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead
更正后的NSLog
消息实际上是NSLog(@"%lg", (long) myInt);
.如果要显示值,为什么必须将 myInt
的整数值转换为 long
?
The corrected NSLog
message is actually NSLog(@"%lg", (long) myInt);
. Why do I have to convert the integer value of myInt
to long
if I want the value to display?
推荐答案
如果你在 OS X(64 位)上编译你会收到这个警告,因为在那个平台上 NSInteger
被定义为 long
是一个 64 位整数.另一方面,%i
格式用于 int
,它是 32 位的.所以格式和实际参数大小不匹配.
You get this warning if you compile on OS X (64-bit), because on that platform NSInteger
is defined as long
and is a 64-bit integer. The %i
format, on the other hand, is for int
, which is 32-bit. So the format and the actual parameter do not match in size.
由于 NSInteger
是 32 位还是 64 位,根据平台不同,编译器推荐通常向 long
添加一个强制转换.
Since NSInteger
is 32-bit or 64-bit, depending on the platform, the compiler recommends
to add a cast to long
generally.
更新: 由于 iOS 7 现在也支持 64 位,因此您在编译时会收到相同的警告适用于 iOS.
Update: Since iOS 7 supports 64-bit now as well, you can get the same warning when compiling for iOS.
这篇关于为什么 NSInteger 变量在用作格式参数时必须强制转换为 long?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!