I am trying to figure out the best way to convert an NSUInteger into a string that works for both 32- and 64-bit systems. I see that NSUInteger is defined differently for both platforms and I want to make sure what I am doing is correct.
All solutions I have seen required some casting, or seem incorrect. I get a warning with the code below asking me to add an explicit cast.
NSUInteger unsignedInteger = PostStatusFailed; // This is an enum
NSString *string = [NSString stringWithFormat:@"postStatus == %lu", unsignedInteger];
I have also tried %d (signed ints, which doesn't seem correct), and %lx, but none seem correct. Thanks.
From the String Programming Guide:
OS X uses several data types—
NSInteger,NSUInteger,CGFloat, andCFIndex—to provide a consistent means of representing values in 32- and 64-bit environments. In a 32-bit environment,NSIntegerandNSUIntegerare defined asintandunsigned int, respectively. In 64-bit environments,NSIntegerandNSUIntegerare defined aslongandunsigned long, respectively. To avoid the need to use different printf-style type specifiers depending on the platform, you can use the specifiers shown in Table 3. Note that in some cases you may have to cast the value.
See the link for all of the types. For NSUInteger, the correct approach is:
NSUInteger i = 42;
NSString *numberString = [NSString stringWithFormat:@"%lu is the answer to life, the universe, and everything.", (unsigned long)i];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With