我应该如何将int传递给stringWithFormat?

Bre*_*nan 66 cocoa-touch objective-c

我尝试使用stringWithFormat在标签的text属性上设置数值,但以下代码不起作用.我无法将int转换为NSString.我期待该方法知道如何自动将int转换为NSString.

我需要做什么?

- (IBAction) increment: (id) sender
{
    int count = 1;
    label.text = [NSString stringWithFormat:@"%@", count];
}
Run Code Online (Sandbox Code Playgroud)

Bob*_*toe 126

做这个:

label.text = [NSString stringWithFormat:@"%d", count];
Run Code Online (Sandbox Code Playgroud)

  • 在为64位设备编译时会产生警告,其中`int`实际上是`long`. (8认同)

Mar*_*eau 47

请记住,@"%d"仅适用于32位.如果您编译64位平台,一旦开始使用NSInteger兼容性,您应该使用@"%ld"作为格式说明符.


squ*_*art 40

Marc Charbonneau写道:

请记住,@"%d"仅适用于32位.如果您编译64位平台,一旦开始使用NSInteger兼容性,您应该使用@"%ld"作为格式说明符.

有意思,感谢小费,我正在使用@"%d"和我的NSIntegers!

SDK文档还建议在这种情况下强制NSInteger转换long(以匹配@"%ld"),例如:

NSInteger i = 42;
label.text = [NSString stringWithFormat:@"%ld", (long)i];
Run Code Online (Sandbox Code Playgroud)

来源:Cocoa字符串编程指南 - 字符串格式说明符(需要iPhone开发人员注册)


Zac*_*ley 24

你想使用%d%i整数.%@用于对象.

但值得注意的是,以下代码将完成相同的任务并且更加清晰.

label.intValue = count;
Run Code Online (Sandbox Code Playgroud)


squ*_*art 13

而对于喜剧价值:

label.text = [NSString stringWithFormat:@"%@", [NSNumber numberWithInt:count]];
Run Code Online (Sandbox Code Playgroud)

(虽然如果有一天你在处理NSNumber的话可能会有用)

  • 或者使用现代的objective-c语法并使用:[NSString stringWithFormat:@"%@",@(count)] (3认同)

ohh*_*hho 6

要成为32位和64位安全,请使用其中一个Boxed表达式:

  label.text = [NSString stringWithFormat:@"%@", @(count).stringValue];
Run Code Online (Sandbox Code Playgroud)