简体   繁体   中英

NSUInteger string encoding 32 and 64 bit

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 , and CFIndex —to provide a consistent means of representing values in 32- and 64-bit environments. In a 32-bit environment, NSInteger and NSUInteger are defined as int and unsigned int , respectively. In 64-bit environments, NSInteger and NSUInteger are defined as long and unsigned 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];

According to the 64-bit Transition Guide :

The compiler defines the LP64 macro when compiling for the 64-bit runtime.

So you can do something like this:

#if __LP64__
    NSString *string = [NSString stringWithFormat:@"postStatus == %lu", unsignedInteger];
#else
    NSString *string = [NSString stringWithFormat:@"postStatus == %u", unsignedInteger];
#endif

In a 32-bit environment, NSInteger and NSUInteger are defined as int and unsigned int, respectively. In 64-bit environments, NSInteger and NSUInteger are defined as long and unsigned long, respectively.

so have a NSNumber for best way.

when you want get a NSString, like this formate to NSNumber then.

NSUInteger unsignedInteger = PostStatusFailed; // This is an enum
NSString *string = [NSString stringWithFormat:@"postStatus == %@", @(unsignedInteger)];

%@ ---> @(NSUInteger), you see @(), it's a NSNumber.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM