简体   繁体   English

如何将NSInteger转换为NSString数据类型?

[英]How do I convert NSInteger to NSString datatype?

How does one convert NSInteger to the NSString datatype? 如何将NSInteger转换为NSString数据类型?

I tried the following, where month is an NSInteger : 我试过以下,其中月是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 现代目标-C

An NSInteger has the method stringValue that can be used even with a literal NSInteger的方法stringValue甚至可以用于文字

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. %zd适用于NSIntegers(NSUInteger的%tu ),在32位和64位体系结构上没有强制转换,也没有警告。 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 . 这里@(value)将给定的NSInteger转换为NSNumber对象,您可以为其调用所需的函数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获取字符串的有趣方式

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

NSNumber may be good for you in this case. 在这种情况下,NSNumber可能对你有好处。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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