【问题标题】:how to convert integer to string? [duplicate]如何将整数转换为字符串? [复制]
【发布时间】:2011-03-25 18:51:32
【问题描述】:

可能重复:
How to convert from int to string in objective c: example code…

如何在 Objective C 中将整数转换为字符串?

【问题讨论】:

  • 您作为重复链接到的另一个问题与此问题具有相同的标题,并且具有 9000 多个视图,但它没有直接和明确地回答标题中的问题:如何在 Objecive-C 中将 int 转换为 string。另一个问题很复杂,很难从中提取真正的答案。实际上,发现它的人更有可能学习如何(不)比较字符串,而不是如何将 int 转换为 NSString。

标签: objective-c


【解决方案1】:
NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

【讨论】:

  • 我收到下一个警报:'NSInteger' 类型的值不应用作格式参数;改为向“long”添加显式强制转换,为什么?
【解决方案2】:

如果你真的想使用字符串:

NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];

但我建议使用 NSNumber:

NSNumber *number = [[NSNumber alloc] initWithInt:123];

然后将其添加到数组中。

[array addObject:number];

不要忘记在那之后释放它,因为你在上面创建了它。

[number release];

【讨论】:

    【解决方案3】:
    NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];
    

    更新新的 Objective-C 语法:

    NSArray *myArray = @[@1, @2, @3];
    

    从编译器的角度来看,这两个声明是相同的。

    如果您只是想在字符串中使用整数来放入文本框或其他内容:

    int myInteger = 5;
    NSString* myNewString = [NSString stringWithFormat:@"%i", myInteger];
    

    【讨论】:

      猜你喜欢
      • 2012-04-30
      • 2020-10-24
      • 2011-12-27
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 2012-03-28
      相关资源
      最近更新 更多