NSInteger myInt = 1804809223;
NSLog(@"%i", myInt); <====
Run Code Online (Sandbox Code Playgroud)
上面的代码产生错误:
Values of type "NSInteger" should not be used as format arguments: add an explicit cast to 'long' instead.
Run Code Online (Sandbox Code Playgroud)
正确的NSLog消息实际上NSLog(@"%lg", (long) myInt);为什么我要将myInt的整数值转换为long,如果我想要显示该值?
A NSInteger在32位平台上为32位,在64位平台上为64位.是否有一个NSLog总是匹配大小的说明符NSInteger?
建立
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;
}
Run Code Online (Sandbox Code Playgroud)
对于32位代码,我需要说明%d符.但是,如果我使用说明%d符,我在编译64位时会收到警告,建议我使用%ld.
如果我使用%ld匹配64位大小,编译32位代码时,我会收到警告,建议我使用%d.
如何一次修复这两个警告?是否有我可以使用的说明符?
这也影响[NSString stringWithFormat:]和[[NSString alloc] initWithFormat:].
编译我的iOS应用程序的arm64代码我遇到了一个有趣的问题,与自定义Foundation类型的不同基本类型有关.假设我想printf(或stringWithFormat)一个声明为NSUInteger的数字
[NSString stringWithFormat:@"%u", _depth,
Run Code Online (Sandbox Code Playgroud)
这将为arm64生成一个警告编译,因为NSUInteger为arm64声明为unsigned long.因此,我应该用"%lu"替换"%u",但现在在编译armv7(s)体系结构时这变得无效,因为对于32位体系结构,NSUInteger声明为unsigned int.我知道警告说"NSUInteger不应该用作格式参数",所以让我们继续浮动:
typedef CGFLOAT_TYPE CGFloat;
Run Code Online (Sandbox Code Playgroud)
在64位CGFLOAT_TYPE上是双倍的,而在32位上它是浮点数.因此,做这样的事情:
- (void)foo:(CGFloat)value;
Run Code Online (Sandbox Code Playgroud)
然后
[self foo:10.0f];
[self foo:10.0];
Run Code Online (Sandbox Code Playgroud)
在编译两个体系结构时仍会产生警告.在32位架构上,第二次调用不正确(从double转换为float),在64-bt架构上,第一次将float转换为double(这是好的,但仍然不好).
很想听听你对这个问题的看法.
我在Mac OS X应用程序中有以下代码行:
NSLog(@"number of items: %ld", [urlArray count]);
Run Code Online (Sandbox Code Playgroud)
我收到警告:"格式指定类型'long'但参数的类型为'NSUInteger'(又名'unsigned int')"
但是,如果我将我的代码更改为:
NSLog(@"number of items: %u", [urlArray count]);
Run Code Online (Sandbox Code Playgroud)
我收到警告:
Format指定类型'unsigned int'但参数的类型为'NSUInteger'(又名'unsigned long')
所以我把它改成了
NSLog(@"number of items: %u", [urlArray count]);
Run Code Online (Sandbox Code Playgroud)
但我收到警告:Format指定类型'unsigned long'但参数的类型为'NSUInteger'(又名'unsigned int')
如何设置我的NSLog以便它不会生成警告?如果我遵循Xcode的建议,我只是进入一个无限循环的更改格式说明符,但警告永远不会消失.