Objective C 警告 Values of type 'NSUInteger' should not be used as format arguments

Objective C 2020-02-15 阅读 105 评论 0

警告的出现

在使用 Objective C 的 NSLog 打印数组的长度或者使用 NSUInteger变量。

// 定义一个数组
NSArray *arr = @[@"1", @"2"];
NSLog(@"%d", [arr count]);

Xcode 提醒一个警告

Values of type 'NSUInteger' should not be used as format arguments; add an explicit cast to 'unsigned long' instead
Replace '%d", ' with '%lu", (unsigned long)'

解决

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

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

实际上,几乎没有什么工作要做,因为 Xcode 的 Fix-It 功能将自动完成此操作。

NSArray *arr = @[@"1", @"2"];
NSLog(@"%lu", (unsigned long)[arr count]);
// 或者
NSLog(@"%ld", [arr count]);

警告就消失了。

最后更新 2020-02-15