NSUInteger不应该用于格式字符串?

时间:2014-03-26 19:36:27

标签: objective-c

这是我的代码中的所有荣耀:

[NSString stringWithFormat:@"Total Properties: %d", (int)[inArray count]];

这让我得到了Xcode 5.1警告:

Values of type 'NSUInteger' should not be used as format arguments; add an explicit cast to 'unsigned long' instead

好的,我很困惑。该值实际上是一个32位的int,我把它转换为32位int。那么这个NSUInteger抱怨的是什么(我假设的数量)以及为什么这个演员不会修复它?

4 个答案:

答案 0 :(得分:91)

NSUInteger和NSInteger在32位(int)和64位(long)上的长度不同。为了使一个格式说明符适用于两个体系结构,必须使用long说明符并将值转换为long:

Type    Format Specifier    Cast
----    ----------------    ----
NSInteger    %ld            long
NSUInteger   %lu            unsigned long

因此,例如,您的代码变为:

[NSString stringWithFormat:@"Total Properties: %lu", (unsigned long)[inArray count]];

真的很少有工作要做,因为Xcode的Fix-It功能会自动为你做这件事。

答案 1 :(得分:44)

也可以将“z”和“t”修饰符用于与CPU无关的格式字符串,例如

NSInteger x = -1;
NSUInteger y = 99;
NSString *foo = [NSString stringWithFormat:@"NSInteger: %zd, NSUInteger: %tu", x, y];

答案 2 :(得分:8)

NSUInteger的基础类型基于平台发生变化:它是32位平台上的32位无符号整数,64位平台上的64位无符号整数。

Platform Dependencies section on of the String Programming Guide Apple中建议您执行以下操作:

  

为了避免根据平台使用不同的printf样式类型说明符,可以使用表3中所示的说明符。请注意,在某些情况下,您可能必须转换值。

     

对于NSUInteger使用格式%lu%lx,并将值转换为unsigned long

因此,您的代码需要按如下方式进行更改,以避免出现警告:

[NSString stringWithFormat:@"Total Properties: %lu", (unsigned long)[inArray count]];

答案 3 :(得分:0)

您也可以尝试使用NSNumber方法:

[NSString stringWithFormat:@"Total Properties: %@", [[NSNumber numberWithUnsignedInteger:[inArray count]] stringValue]];
相关问题