How do I convert NSInteger to NSString datatype?

IosIphoneNsstringNsinteger

Ios Problem Overview


How does one convert NSInteger to the NSString datatype?

I tried the following, where month is an NSInteger:

  NSString *inStr = [NSString stringWithFormat:@"%d", [month intValue]];

Ios Solutions


Solution 1 - Ios

NSIntegers are not objects, you cast them to long, in order to match the current 64-bit architectures' definition:

NSString *inStr = [NSString stringWithFormat: @"%ld", (long)month];

Solution 2 - Ios

Obj-C way =):

NSString *inStr = [@(month) stringValue];

Solution 3 - Ios

Modern Objective-C

An NSInteger has the method stringValue that can be used even with a literal

NSString *integerAsString1 = [@12 stringValue];

NSInteger number = 13;
NSString *integerAsString2 = [@(number) stringValue];

Very simple. Isn't it?

Swift

var integerAsString = String(integer)

Solution 4 - Ios

%zd works for NSIntegers (%tu for NSUInteger) with no casts and no warnings on both 32-bit and 64-bit architectures. I have no idea why this is not the "recommended way".

NSString *string = [NSString stringWithFormat:@"%zd", month];

If you're interested in why this works see this question.

Solution 5 - Ios

Easy way to do:

NSInteger value = x;
NSString *string = [@(value) stringValue];

Here the @(value) converts the given NSInteger to an NSNumber object for which you can call the required function, stringValue.

Solution 6 - Ios

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

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

Solution 7 - Ios

You can also try:

NSInteger month = 1;
NSString *inStr = [NSString stringWithFormat: @"%ld", month];

Solution 8 - Ios

The answer is given but think that for some situation this will be also interesting way to get string from NSInteger

NSInteger value = 12;
NSString * string = [NSString stringWithFormat:@"%0.0f", (float)value];

Solution 9 - Ios

NSNumber may be good for you in this case.

NSString *inStr = [NSString stringWithFormat:@"%d", 
                    [NSNumber numberWithInteger:[month intValue]]];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsenthilMView Question on Stackoverflow
Solution 1 - IosluvieereView Answer on Stackoverflow
Solution 2 - IosAlexey KozhevnikovView Answer on Stackoverflow
Solution 3 - IosMadNikView Answer on Stackoverflow
Solution 4 - IosKevinView Answer on Stackoverflow
Solution 5 - IosKarthik damodaraView Answer on Stackoverflow
Solution 6 - IosAndreas LeyView Answer on Stackoverflow
Solution 7 - IosNeverHopelessView Answer on Stackoverflow
Solution 8 - IosNazirView Answer on Stackoverflow
Solution 9 - IoshotheadView Answer on Stackoverflow