Implicit conversion loses the whole precision: 'long long' to 'NSInteger' (aka 'int')

I am trying to assign a variable of type long long to type NSUInteger. What is the right way to do this?

my line of code:

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

where expectedSizeis of type NSUInteger, and the return response.expectedContentLengthtype is of type " long long". The variable responseis of type NSURLResponse.

Compilation error shown:

Semantic problem: implicit conversion loses the whole precision: 'long long' to 'NSUInteger' (aka 'unsigned int')

+5
source share
2 answers

It's really just a cast with some range checking:

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
source

NSNumber:

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

All Articles