【问题标题】:Append text with variables Objective C附加带有变量的文本Objective C
【发布时间】:2013-05-04 13:39:20
【问题描述】:

在尝试此操作之前,我一直在尝试附加文本但没有成功:

NSString *n_result = @"";
n_result = [n_result stringByAppendingString:[NSString stringWithFormat:@"The number "]];
    n_result = [n_result stringByAppendingString:[NSString stringWithFormat:@"%@ ", n_analyze]];
    n_result = [n_result stringByAppendingString:[NSString stringWithFormat:@", has "]];
    n_result = [n_result stringByAppendingString:[NSString stringWithFormat:@"%i ", steps]];
    n_result = [n_result stringByAppendingString:[NSString stringWithFormat:@"steps to reach 1"]];

问题是,必须有一种更简单的方法来做到这一点。但我不知道怎么做。 谁能帮我这个?我一直在到处寻找如何“更好”地做到这一点。

【问题讨论】:

    标签: objective-c string nsstring append


    【解决方案1】:

    是的,有一个稍微简单的方法。使用NSMutableString的实例

    NSMutableString *mutableString = [NSMutableString stringWithFormat:@"The number "];
    [mutableString appendFormat:@"%@ ", n_analyze];
    
    // etc.. 
    

    【讨论】:

      【解决方案2】:

      [NSString stringWithFormat:@"The number %@ , has %i steps to reach 1", n_analyze, steps]

      【讨论】:

      • 非常感谢您。如果有人想知道 NSString *n_result = @""; 我就这样使用它n_result = [NSString stringWithFormat:@"数字 %@ ,有 %i 步才能达到 1", n_analyze, steps];
      • @LucianoOliveira 无需先分配@""。只需:NSString *n_result = [NSString stringWithFormat:@"The number %@ , has %i steps to reach 1", n_analyze, steps];
      • @LucianoOliveira 在字符串格式过多的项目(我的所有项目)中,我声明 SS() 宏以缩短该语法。 #define SS(fmt,...) [NSString stringWithFormat:fmt, ##__VA_ARGS__].pch 文件中。现在它变成了SS(@"Hi, %@!", username)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 2014-03-17
      相关资源
      最近更新 更多