You don't have to cast to anything if your format specifiers match your data types. See Martin R's answer for details on how NSInteger
is defined in terms of native types.
So for code intended to be built for 64-bit environments, you can write your log statements like this:
NSLog(@"%ld", myInt);
while for 32-bit environments you can write:
NSLog(@"%d", myInt);
and it will all work without casts.
One reason to use casts anyway is that good code tends to be ported across platforms, and if you cast your variables explicitly it will compile cleanly on both 32 and 64 bit:
NSLog(@"%ld", (long)myInt);
And notice this is true not just for NSLog statements, which are just debugging aids after all, but also for [NSString stringWithFormat:]
and the various derived messages, which are legitimate elements of production code.
NSLog(@"%ld", (long) myInt);
, thelong
cast is to make it match up with thel
qualifier of%ld
, but all of that is unnecessary asNSLog(@"%d", myInt);
is sufficient (given that we can see thatmyInt
is notlong
. Bottom line, you castmyInt
if using long qualifier in format string, but no need to use either long string format qualifier orlong
cast here. – CrisisNSInteger
is not long) , but it sounds like you're compiling with OS X target (whereNSInteger
islong
). – Crisis