隐式转换失去整数精度:'long long'到'NSInteger'(又名'int')

时间:2012-05-16 09:43:46

标签: ios ios5 xcode4.2 long-integer nsuinteger

我正在尝试将类型为“long long”的变量分配给NSUInteger类型,这样做的正确方法是什么?

我的代码行:

expectedSize = response.expectedContentLength > 0 ? response.expectedContentLength : 0;

其中expectedSize的类型为NSUInteger,返回类型response.expectedContentLength的类型为“long long”。变量response的类型为NSURLResponse

显示的编译错误是:

  

语义问题:隐式转换失去整数精度:'long   长'到'NSUInteger'(又名'unsigned int')

2 个答案:

答案 0 :(得分:11)

您可以尝试使用NSNumber进行转换:

  NSUInteger expectedSize = 0;
  if (response.expectedContentLength) {
    expectedSize = [NSNumber numberWithLongLong: response.expectedContentLength].unsignedIntValue;
  }

答案 1 :(得分:5)

这只是一个演员,有一些范围检查:

const long long expectedContentLength = response.expectedContentLength;
NSUInteger expectedSize = 0;

if (NSURLResponseUnknownLength == expectedContentLength) {
    assert(0 && "length not known - do something");
    return errval;
}
else if (expectedContentLength < 0) {
    assert(0 && "too little");
    return errval;
}
else if (expectedContentLength > NSUIntegerMax) {
    assert(0 && "too much");
    return errval;
}

// expectedContentLength can be represented as NSUInteger, so cast it:
expectedSize = (NSUInteger)expectedContentLength;