5

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

我的代码行:

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

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

显示的编译错误是:

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

4

2 回答 2

11

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

  NSUInteger expectedSize = 0;
  if (response.expectedContentLength) {
    expectedSize = [NSNumber numberWithLongLong: response.expectedContentLength].unsignedIntValue;
  }
于 2012-05-16T10:30:46.547 回答
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;
于 2012-05-16T10:46:04.323 回答