"NSString stringWithFormat:" with "%zd" curious behavior in 32bit devices

791 Views Asked by At

Why we cannot format string using "%zd" as expected in 32bit devices(iPhone5, iPhone4s or their simulators)?

int64_t test1 = 11111111;
int64_t test2 = 22222222;
int64_t test3 = 33333333;
int64_t test4 = 44444444;
NSString *testStr = [NSString stringWithFormat:@"\"%zd %zd %zd %zd\"", test1, test2, test3, test4];
NSLog(@"testStr: %@", testStr);

NSInteger test5 = 55555555;
NSInteger test6 = 66666666;
NSInteger test7 = 77777777;
NSInteger test8 = 88888888;
testStr = [NSString stringWithFormat:@"\"%zd %zd %zd %zd\"", test5, test6, test7, test8];
NSLog(@"testStr: %@", testStr);

The log is:

2017-09-12 05:53:59.462: testStr:"11111111 0 22222222 0"
2017-09-12 05:53:59.465: testStr:"55555555 66666666 77777777 88888888"
1

There are 1 best solutions below

5
CRD On

Note: Answer just typed in on a tablet, your sample not tested, so this is a guess.

The format %zd is for values of type size_t and not 64-bit values.

Try using %lld for int64_t values, long long is 64 bits on both 32-bit and 64-bit iOS versions.

For NSInteger try %ld and cast the arguments to long, this is because the size of NSInteger is dependent on platform.

HTH