0

When I use %d with an NSInteger, Xcode suggests using %ld and casting the NSInteger with (long). But when I just use %ld without the (long)myNSInteger, the warning goes away.

Which should I use?

quantumpotato
  • 9,637
  • 14
  • 70
  • 146

2 Answers2

1

From Apple's headers:

#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif

So the type of NSInteger is either int or long, depending on the target platform. You're not getting a warning when you don't cast because you're (most likely) running on a 64 bit platform. If you target a 32bit platform, you'll get a warning without the cast.

You can use %zd, which will always work without the cast on 32bit and 64bit platforms (but only for signed integers—I think).

You can do something like this and not ever worry about it (but there is a performance hit):

NSInteger myNSInteger = 12345;
[NSString stringWithFormat:@"%@", @(myNSInteger)];
i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
0

Depends on the device in the simulator: With iPhone 5 or less, NSinteger is 32 bits, and %d is ok, if you use %ld you should cast with (long). With iPhone 5S or more, NSInteger is 64 bits, and %ld is ok.

The best option to don't have any warning is ld and cast all (long).

Onik IV
  • 5,007
  • 2
  • 18
  • 23