简体   繁体   中英

How do I convert NSInteger to NSString datatype?

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]];

NSIntegers不是对象,您将它们转换为long ,以匹配当前的64位体系结构的定义:

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

Obj-C方式=):

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

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)

%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 .

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 .

在编译支持arm64 ,这不会产生警告:

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

You can also try:

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

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];

NSNumber may be good for you in this case.

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

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