NSLog / printf说明符为NSInteger? [英] NSLog/printf specifier for NSInteger?
问题描述
A NSInteger
在32位平台上为32位,在64位平台上为64位。是否有 NSLog
说明符总是匹配 NSInteger
?
设置
- Xcode 3.2.5
- llvm 1.6编译器重要; gcc不这样做)
-
GCC_WARN_TYPECHECK_CALLS_TO_PRINTF
已启用
这让我有些悲伤:
#import /Foundation.h>
int main(int argc,const char * argv []){
@autoreleasepool {
NSInteger i = 0;
NSLog(@%d,i);
}
return 0;
}
对于32位代码,我需要%d
说明符。但是如果我使用%d
说明符,我在编译64位时收到警告,表明我使用%ld
。
如果我使用%ld
匹配64位大小,当编译32位代码时,警告提示我使用%d
。
如何同时修复这两个警告?是否有一个我可以使用的说明符可以工作?
这也影响 [NSString stringWithFormat:]
code> [[NSString alloc] initWithFormat:] 。
/ p>
使用当前Xcode,您可以使用 z
和 t
modifiers在所有体系结构上处理 NSInteger
和 NSUInteger
您要使用%zd
作为签名,%tu
表示未签名, c $ c>%tx (十六进制)。
此信息由 Greg Parker 。
原始回答:
官方推荐方法是使用%ld
作为您的说明符,并将实际参数转换为 long
。
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
?
Setup
- Xcode 3.2.5
- llvm 1.6 compiler (this is important; gcc doesn't do this)
GCC_WARN_TYPECHECK_CALLS_TO_PRINTF
turned on
That's causing me some grief here:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
@autoreleasepool {
NSInteger i = 0;
NSLog(@"%d", i);
}
return 0;
}
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.
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?
This also impacts [NSString stringWithFormat:]
and [[NSString alloc] initWithFormat:]
.
Updated answer:
With current Xcode, you can make use of the z
and t
modifiers to handle NSInteger
and NSUInteger
without warnings, on all architectures.
You want to use %zd
for signed, %tu
for unsigned, and %tx
for hex.
This information comes courtesy of Greg Parker.
Original answer:
The official recommended approach is to use %ld
as your specifier, and to cast the actual argument to a long
.
这篇关于NSLog / printf说明符为NSInteger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!