How to covert an NSUInteger / NSInteger into an int value

- by

Before the addition of 64bit in iOS it was possible to take an NSUInteger (or NSInteger) and put it into an int variable, like so:

int arrayCount = [self.myArray count];

If you add 64bit support to your app you may notice a compiler warning when you do this:

Implicit conversion loses integer precision: ‘NSInteger’ (aka ‘long’) to ‘int’

Your code will still work, but what Xcode is saying here is that in 64bit an NSInteger is not the same as an int value because it’s classic C and still 32bit. Upon conversion half those bits are cut off.

This is not a problem if your value is anywhere between 0 and 4,294,967,295 (or between −2,147,483,648 and 2,147,483,647 respectively).

But a 64bit integer can hold values between 0 and 18,446,744,073,709,551,615 (or between −9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 respectively) – which even if we can’t imagine or read such a number, it appears considerably higher than the one above.

Those scary values aside, how do we tell Xcode that “it’s fine to drop several gazillion from my array with 12 items”?

We can use typecasting. Rather than “implying” that we’d like to convert the value, we explicitly tell Xcode to do so:

int arrayCount = (int)[self.myArray count];

Xcode understands that this is intentional and drops the warning.

If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.