Search code examples
objective-cnsinteger

String formatting %ld for NSInteger suggests (long)?


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?


Solution

  • 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)];