Objective-C隐式转换将整数精度'NSUInteger'(aka'unsigned long')转换为'int'警告 [英] Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

查看:821
本文介绍了Objective-C隐式转换将整数精度'NSUInteger'(aka'unsigned long')转换为'int'警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些练习,并且收到警告,指出:

I'm working through some exercises and have got a warning that states:

隐式转换将失去整数精度:将'NSUInteger'(aka'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;
}

推荐答案

NSArraycount方法返回NSUInteger,并且在64位OS X平台上

The count method of NSArray returns an NSUInteger, and on the 64-bit OS X platform

  • NSUInteger定义为unsigned long,并且
  • unsigned long是64位无符号整数.
  • int是32位整数.
  • NSUInteger is defined as unsigned long, and
  • unsigned long is a 64-bit unsigned integer.
  • int is a 32-bit integer.

因此int的数据类型比NSUInteger小,因此是编译器警告.

So int is a "smaller" datatype than NSUInteger, therefore the compiler warning.

另请参见:

在构建32位应用程序时,NSUInteger是32位无符号的 整数. 64位应用程序将NSUInteger视为64位无符号 整数.

When building 32-bit applications, NSUInteger is a 32-bit unsigned integer. A 64-bit application treats NSUInteger as a 64-bit unsigned integer.

要解决该编译器警告,可以将本地count变量声明为

To fix that compiler warning, you can either declare the local count variable as

NSUInteger count;

或(如果您确定数组不会包含超过2^31-1个元素!), 添加一个明确的演员表:

or (if you are sure that your array will never contain more than 2^31-1 elements!), add an explicit cast:

int count = (int)[myColors count];

这篇关于Objective-C隐式转换将整数精度'NSUInteger'(aka'unsigned long')转换为'int'警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆