How do you convert an NSUInteger into an NSString?

25.6k views Asked by At

How do you convert an NSUInteger into an NSString? I've tried but my NSString returned 0 all the time.

NSUInteger NamesCategoriesNSArrayCount = [self.NamesCategoriesNSArray count];  
NSLog(@"--- %d", NamesCategoriesNSArrayCount);  
[NamesCategoriesNSArrayCountString setText:[NSString stringWithFormat:@"%d",    NamesCategoriesNSArrayCount]];  
NSLog(@"=== %d", NamesCategoriesNSArrayCountString);
5

There are 5 answers

3
Andreas Ley On

When compiling with support for arm64, this won't generate a warning:

[NSString stringWithFormat:@"%lu", (unsigned long)myNSUInteger];
3
Raj On

I hope your NamesCategoriesNSArrayCountString is NSString; if yes use the below line of code.

NamesCategoriesNSArrayCountString  = [NSString stringWithFormat:@"%d", NamesCategoriesNSArrayCount]];

istead of

[NamesCategoriesNSArrayCountString setText:[NSString stringWithFormat:@"%d", NamesCategoriesNSArrayCount]];
0
Reefwing On

You can also use:

NSString *rowString = [NSString stringWithFormat: @"%@",  @(row)];

where row is a NSUInteger.

0
Nate On

This String Format Specifiers article from Apple is specific when you need to format Apple types:

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.

  • [NSString stringWithFormat:@"%ld", (long)value] : NSInteger displayed as decimal
  • [NSString stringWithFormat:@"%lx", (long)value] : NSInteger displayed as hex
  • [NSString stringWithFormat:@"%lu", (unsigned long)value] : NSUInteger displayed as decimal
  • [NSString stringWithFormat:@"%lx", (unsigned long)value] : NSUInteger displayed as hex
  • [NSString stringWithFormat:@"%f", value] : CGFloat
  • [NSString stringWithFormat:@"%ld", (long)value] : CFIndex displayed as decimal
  • [NSString stringWithFormat:@"%lx", (long)value] : CFIndex displayed as hex

See the article for more details.

2
Paul Peelen On

When compiling for arm64, use the following to avoid warnings:

[NSString stringWithFormat:@"%tu", myNSUInteger];

Or, in your case:

NSUInteger namesCategoriesNSArrayCount = [self.NamesCategoriesNSArray count];  
NSLog(@"--- %tu", namesCategoriesNSArrayCount);  
[namesCategoriesNSArrayCountString setText:[NSString stringWithFormat:@"%tu", namesCategoriesNSArrayCount]];  
NSLog(@"=== %@", namesCategoriesNSArrayCountString);

(Also, tip: Variables start with lowercase. Info: here)