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

150

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

我尝试了以下代码,其中 month 是一个 NSInteger

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

281

NSIntegers不是对象,你需要将它们转换成long,以便与当前的64位架构定义相匹配:

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

(NSIntegers are not objects, 您需要将它们转换为long,以便与当前的64位体系结构定义相匹配:)

11
我尝试了这个操作,但是不断收到一个警告:Format specifies type 'int' but the argument has type 'NSInteger *'(aka 'int *')。根据苹果文档,我改用 NSString *inStr = [NSString stringWithFormat:@"%d", (int)month]; - Steven
8
请注意,在64位处理器上(比如新的A7芯片),如果您的应用程序编译成64位,NSInteger实际上是一个long而不是int。在通用情况下,在64位平台上进行(int)month强制转换将是有害的。如果只针对苹果平台,请使用Objective-C方式,就像Aleksey Kozhevnikov的答案中所示,或者类似的可以同时使用int和long的方法,例如long ;-)Andreas Ley的答案中提供了一个无符号的例子(意味着非负数)。 - Louis St-Amour
1
@Steven 我已经尝试删除答案,以便让当前更适用的答案浮现并被接受,但显然,已接受的答案无法删除。因此,我至少尝试调整其内容,为寻找快速解决方案且不触发警告的人们提供尽可能多的有用信息。 - luvieere
@luvieere Apple的文档清楚地解释了如何在格式字符串中处理NSInteger。您应该更新您的答案以遵循这个建议。 - Nikolai Ruhe
3
[@(integerValue) stringValue] 是一个更简洁的方法。 - Zorayr

194

Obj-C 的做法 =):

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

这就是方法。 - Jan Z.

85

现代化的Objective-C

NSInteger具有stringValue方法,即使在文字中也可以使用。

NSString *integerAsString1 = [@12 stringValue];

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

非常简单。不是吗?

Swift

var integerAsString = String(integer)

8

%zd 可以用于不需要强制转换且在32位和64位架构上都没有警告的NSIntegers(%tu 可用于NSUInteger)。我不知道为什么这不是“推荐使用的方式”。

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

如果您对这个方法为什么有效感兴趣,请查看此问题

5

简单易行的方法:

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

在这里,@(value)将给定的NSInteger转换为NSNumber对象,从而可以调用所需的函数stringValue

2

您也可以尝试:

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

2
编译时启用arm64支持时,将不会生成警告:
[NSString stringWithFormat:@"%lu", (unsigned long)myNSUInteger];

0

答案已经给出,但是对于某些情况来说,从NSInteger获取字符串也是一种有趣的方式。

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

0

在这种情况下,NSNumber可能适合您。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接