mon*_*boy 182 objective-c compiler-warnings implicit-conversion
我正在进行一些练习,并得到一个警告:
隐式转换失去整数精度'NSUInteger'(又名'unsigned long')到'int'
我很喜欢这个菜鸟,非常感谢任何帮助..谢谢.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSArray *myColors;
int i;
int count;
myColors = @[@"Red", @"Green", @"Blue", @"Yellow"];
count = myColors.count; // <<< issue warning here
for (i = 0; i < count; i++)
NSLog (@"Element %i = %@", i, [myColors objectAtIndex: i]);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 461
所述count的方法NSArray返回的NSUInteger,并且64位OS X平台上
NSUInteger定义为unsigned long,和unsigned long 是64位无符号整数.int 是一个32位整数.因此int是一个"较小"的数据类型NSUInteger,因此编译器警告.
另请参阅"基础数据类型参考"中的NSUInteger:
构建32位应用程序时,NSUInteger是一个32位无符号整数.64位应用程序将NSUInteger视为64位无符号整数.
要修复该编译器警告,您可以将局部count变量声明为
NSUInteger count;
Run Code Online (Sandbox Code Playgroud)
或者(如果你确定你的数组永远不会包含多个2^31-1元素!),添加一个显式的强制转换:
int count = (int)[myColors count];
Run Code Online (Sandbox Code Playgroud)
Adr*_*ian 24
与Martin的回答相反,即使你知道你的数组没有超过2 ^ 31-1个元素,转换为int(或忽略警告)并不总是安全的.不是在编译64位时.
例如:
NSArray *array = @[@"a", @"b", @"c"];
int i = (int) [array indexOfObject:@"d"];
// indexOfObject returned NSNotFound, which is NSIntegerMax, which is LONG_MAX in 64 bit.
// We cast this to int and got -1.
// But -1 != NSNotFound. Trouble ahead!
if (i == NSNotFound) {
// thought we'd get here, but we don't
NSLog(@"it's not here");
}
else {
// this is what actually happens
NSLog(@"it's here: %d", i);
// **** crash horribly ****
NSLog(@"the object is %@", array[i]);
}
Run Code Online (Sandbox Code Playgroud)
在“项目”>“构建设置”中更改键“ 对printf / scanf进行类型检查调用:否 ”
说明: [如何运作]
检查对printf和scanf等的调用,以确保提供的参数具有与指定的格式字符串相对应的类型,并且确保在格式字符串中指定的转换有意义。
希望它能工作
其他警告
目标c隐式转换将整数精度'NSUInteger'(aka'unsigned long')转换为'int
将密钥“ 隐式转换为32Bits类型>调试> * 64体系结构:否 ”
[ 注意:可能会使64位架构转换的其他警告无效]。
| 归档时间: |
|
| 查看次数: |
145286 次 |
| 最近记录: |