Why does an NSInteger variable have to be cast to long when used as a format argument?

后端 未结 5 1112
借酒劲吻你
借酒劲吻你 2020-12-02 06:56
NSInteger myInt = 1804809223;
NSLog(@\"%i\", myInt); <==== 

The code above produces an error:

Values of type \'NSInteger\

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 07:16

    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.

提交回复
热议问题