7

I have the following line of code in my Mac OS X application:

NSLog(@"number of items: %ld", [urlArray count]);

And I get the warning: "Format specifies type 'long' but the argument has type 'NSUInteger' (aka 'unsigned int')"

However, if I change my code to:

NSLog(@"number of items: %u", [urlArray count]);

I get the warning:

Format specifies type 'unsigned int' but the argument has type 'NSUInteger' (aka 'unsigned long')

So then I change it to

NSLog(@"number of items: %u", [urlArray count]);

but I get the warning: Format specifies type 'unsigned long' but the argument has type 'NSUInteger' (aka 'unsigned int')

How can I set up my NSLog so it does not generate a warning? If I follow Xcode's suggestions i just get into in an endless loop of changing the format specifier but the warnings never go away.

Jackson
  • 3,555
  • 3
  • 34
  • 50

3 Answers3

14

Yeah this is annoying. It is a 32/64 bit thing I believe. The easiest thing to do is just cast to a long:

NSLog(@"number of items: %lu", (unsigned long)[urlArray count]);
D.C.
  • 15,340
  • 19
  • 71
  • 102
6

The portability guide for universal applications suggest casting in this case.

NSLog(@"number of items: %ld", (unsigned long)[urlArray count]);
jarjar
  • 1,681
  • 2
  • 15
  • 19
  • That seems rather unnecessary but it does clear up the warnings. – Jackson Nov 13 '12 at 06:34
  • 3
    Not sure if it makes a difference but you should probably case to the same type as the format specifier. So (unsigned long) would be %lu, or (long) would be %ld – D.C. Nov 13 '12 at 06:35
  • @darren it does make a difference, not doing so is undefined behavior. –  Nov 13 '12 at 06:35
  • From the portability guide: Typically, in 32-bit code you use the %d specifier to format int values in functions such as printf, NSAssert, and NSLog, and in methods such as stringWithFormat:. But with NSInteger, which on 64-bit architectures is the same size as long, you need to use the %ld specifier. Unless you are building 32-bit like 64-bit, these specifiers generates compiler warnings in 32-bit mode. To avoid this problem, you can cast the values to long or unsigned long, as appropriate. For example: NSInteger i = 34; printf("%ld\n", (long)i); – Jackson Nov 13 '12 at 06:36
2

Another option is mentioned here: NSInteger and NSUInteger in a mixed 64bit / 32bit environment

NSLog(@"Number is %@", @(number));
Community
  • 1
  • 1
geowar
  • 4,397
  • 1
  • 28
  • 24