How to covert an NSUInteger / NSInteger into an int value

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.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.