为什么当用作格式参数时,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); <====
上述代码产生错误:
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 correct 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
格式是用于32位的 int
。
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屋!