objective c隐式转换丢失整数精度'NSUInteger'(又名'unsigned long')到'int'警告

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)

  • 只是添加 - 我投了这个答案,因为我在Xcode 5项目中突然收到了大量的警告和错误.你提到了64位,它让我看看我的构建设置.Xcode将其更改为64位模式,这会导致错误.将其更改回arvm7会修复所有这些问题. (18认同)
  • "从2015年2月1日开始,上传到App Store**的新iOS应用程序必须包括64位支持**..." - [Apple Developer News and Updates,2014年10月20日](https://developer.apple .COM /新闻/?ID = 10202014a) (7认同)
  • @JayprakashDubey:Apple没有看到您的编译器警告,因为您将二进制编译的应用程序提交到App Store.因此,由于编译器警告,您的应用程序无法被拒绝.当然你应该修复它们以使你的应用程序正常工作. (2认同)

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)

  • 你是正确的,铸造`indexOfObject:`的结果将是一个坏主意.我的回答是针对问题中的特定代码,而`count`方法不能返回`NSNotFound`.我建议不要强制转换为int或忽略警告.对不起,如果不清楚的话.实际上,如果编译为64位,您的示例代码将在`if(i == NSNotFound)`处生成警告,因此问题不会被忽视. (6认同)
  • 我认为count将比indexOfObject更频繁地使用,并且使用NSInteger膨胀for循环只是为了没有"差"编码风格是无稽之谈.你应该只关注indexOfObject,并确保你在那里使用NSIntegers,所有简单计算的东西都可以作为int,特别是在方法焦点内 (2认同)

Dar*_*hah 5

在“项目”>“构建设置”中更改键“ 对printf / scanf进行类型检查调用

说明: [如何运作]

检查对printf和scanf等的调用,以确保提供的参数具有与指定的格式字符串相对应的类型,并且确保在格式字符串中指定的转换有意义。

希望它能工作

其他警告

目标c隐式转换将整数精度'NSUInteger'(aka'unsigned long')转换为'int

将密钥“ 隐式转换为32Bits类型>调试> * 64体系结构:否

[ 注意:可能会使64位架构转换的其他警告无效]