I'm working through some exercises and have got a warning that states:
implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int'
I'm quite the noob and would appreciate any help.. thanks.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSArray *myColors;
int i;
int count;
myColors = @[@"Red", @"Green", @"Blue", @"Yellow"];
count = myColors.count; // <<< issue warning here
for (i = 0; i < count; i++)
NSLog (@"Element %i = %@", i, [myColors objectAtIndex: i]);
}
return 0;
}
Doing the expicit casting to the "int" solves the problem in my case. I had the same issue. So:
The
count
method ofNSArray
returns anNSUInteger
, and on the 64-bit OS X platformNSUInteger
is defined asunsigned long
, andunsigned long
is a 64-bit unsigned integer.int
is a 32-bit integer.So
int
is a "smaller" datatype thanNSUInteger
, therefore the compiler warning.See also NSUInteger in the "Foundation Data Types Reference":
To fix that compiler warning, you can either declare the local
count
variable asor (if you are sure that your array will never contain more than
2^31-1
elements!), add an explicit cast:Contrary to Martin's answer, casting to int (or ignoring the warning) isn't always safe even if you know your array doesn't have more than 2^31-1 elements. Not when compiling for 64-bit.
For example:
Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"
Explanation : [How it works]
Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.
Hope it work
Other warning
objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int
Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"
[caution: It may void other warning of 64 Bits architecture conversion].