首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >隐式转换失去整数精度:'long long‘to 'NSInteger’(又名'int')

隐式转换失去整数精度:'long long‘to 'NSInteger’(又名'int')
EN

Stack Overflow用户
提问于 2012-05-16 09:43:46
回答 2查看 17.1K关注 0票数 5

我试图将一个类型为' long‘的变量赋值给NSUInteger类型,那么正确的方法是什么呢?

我的代码行:

代码语言:javascript
复制
expectedSize = response.expectedContentLength > 0 ? response.expectedContentLength : 0;

其中expectedSize的类型是NSUInteger,而返回类型的response.expectedContentLength是'long long‘类型。变量responseNSURLResponse类型。

显示的编译错误是:

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-05-16 10:46:04

它实际上只是一个演员,有一些范围检查:

代码语言:javascript
复制
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;
票数 5
EN

Stack Overflow用户

发布于 2012-05-16 10:30:46

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

代码语言:javascript
复制
  NSUInteger expectedSize = 0;
  if (response.expectedContentLength) {
    expectedSize = [NSNumber numberWithLongLong: response.expectedContentLength].unsignedIntValue;
  }
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10615950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档