ios 如何将 NSInteger 转换为 NSString 数据类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1796390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert NSInteger to NSString datatype?
提问by senthilMuthu
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]];
回答by luvieere
NSIntegers are not objects, you cast them to long
, in order to match the current 64-bit architectures' definition:
NSIntegers 不是对象,您将它们强制转换为long
,以匹配当前 64 位架构的定义:
NSString *inStr = [NSString stringWithFormat: @"%ld", (long)month];
NSString *inStr = [NSString stringWithFormat: @"%ld", (long)month];
回答by Alexey Kozhevnikov
Obj-C way =):
Obj-C 方式 =):
NSString *inStr = [@(month) stringValue];
回答by MadNik
Modern Objective-C
现代Objective-C
An NSInteger
has the method stringValue
that can be used even with a literal
AnNSInteger
具有stringValue
即使使用文字也可以使用的方法
NSString *integerAsString1 = [@12 stringValue];
NSInteger number = 13;
NSString *integerAsString2 = [@(number) stringValue];
Very simple. Isn't it?
很简单。不是吗?
Swift
迅速
var integerAsString = String(integer)
回答by Kevin
%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".
%zd
适用于 NSIntegers(%tu
对于 NSUInteger),在 32 位和 64 位架构上没有强制转换和警告。我不知道为什么这不是“推荐的方式”。
NSString *string = [NSString stringWithFormat:@"%zd", month];
If you're interested in why this works see this question.
如果您对为什么这样做感兴趣,请参阅此问题。
回答by Karthik damodara
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
.
回答by Andreas Ley
When compiling with support for arm64
, this won't generate a warning:
编译时支持arm64
,这不会产生警告:
[NSString stringWithFormat:@"%lu", (unsigned long)myNSUInteger];
回答by NeverHopeless
You can also try:
你也可以试试:
NSInteger month = 1;
NSString *inStr = [NSString stringWithFormat: @"%ld", month];
回答by hothead
NSNumber may be good for you in this case.
在这种情况下, NSNumber 可能对你有好处。
NSString *inStr = [NSString stringWithFormat:@"%d",
[NSNumber numberWithInteger:[month intValue]]];
回答by Nazir
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];