NSInteger 的 NSLog/printf 说明符? [英] NSLog/printf specifier for NSInteger?
问题描述
A NSInteger
在 32 位平台上是 32 位,在 64 位平台上是 64 位.是否有一个 NSLog
说明符总是匹配 NSInteger
的大小?
A NSInteger
is 32 bits on 32-bit platforms, and 64 bits on 64-bit platforms. Is there a NSLog
specifier that always matches the size of NSInteger
?
设置
- Xcode 3.2.5
- llvm 1.6 编译器(这很重要;gcc 不这样做)
GCC_WARN_TYPECHECK_CALLS_TO_PRINTF
已开启
这让我有些难过:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
@autoreleasepool {
NSInteger i = 0;
NSLog(@"%d", i);
}
return 0;
}
对于 32 位代码,我需要 %d
说明符.但是,如果我使用 %d
说明符,则在为 64 位编译时会收到警告,建议我改用 %ld
.
For 32 bit code, I need the %d
specifier. But if I use the %d
specifier, I get a warning when compiling for 64 bit suggesting I use %ld
instead.
如果我使用 %ld
来匹配 64 位大小,那么在编译 32 位代码时,我会收到一条警告,建议我改用 %d
.
If I use %ld
to match the 64 bit size, when compiling for 32 bit code I get a warning suggesting I use %d
instead.
如何同时修复这两个警告?是否有我可以使用的说明符?
How do I fix both warnings at once? Is there a specifier I can use that works on either?
这也会影响 [NSString stringWithFormat:]
和 [[NSString alloc] initWithFormat:]
.
推荐答案
更新答案:
您可以使用 z
和 t
修饰符来处理 NSInteger
和 NSUInteger
而没有警告,所有架构.
You can make use of the z
and t
modifiers to handle NSInteger
and NSUInteger
without warnings, on all architectures.
你想用 %zd
表示有符号,%tu
表示无符号,%tx
表示十六进制.
You want to use %zd
for signed, %tu
for unsigned, and %tx
for hex.
此信息由 Greg Parker 提供.
原答案:
官方推荐的方法 是使用 %ld
作为说明符,并将实际参数转换为 long
.
The official recommended approach is to use %ld
as your specifier, and to cast the actual argument to a long
.
这篇关于NSInteger 的 NSLog/printf 说明符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!