0

I was trying to append text without any success until I tryied this:

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"]];

The thing is, there must be a simpler way of doing this. But I don't know how. Can anyone help me with this? I have been searching everywhere how to do this "better".

2 Answers2

3

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

  • Works like a charm thank you very much. I used it like this if anyone wants to know NSString *n_result = @""; n_result = [NSString stringWithFormat:@"The number %@ , has %i steps to reach 1", n_analyze, steps]; – Luciano Oliveira May 09 '13 at 23:15
  • 1
    @LucianoOliveira There is no need to assign `@""` first. Just do: `NSString *n_result = [NSString stringWithFormat:@"The number %@ , has %i steps to reach 1", n_analyze, steps];` – rmaddy May 09 '13 at 23:16
  • @LucianoOliveira In projects with excessive string formatting (all my projects), I declare SS() macro to shorten that syntax. `#define SS(fmt,...) [NSString stringWithFormat:fmt, ##__VA_ARGS__]` in `.pch`-file. Now it becomes `SS(@"Hi, %@!", username)`. –  May 09 '13 at 23:19
3

Yes, there is a slightly easier way. Use an instance of NSMutableString

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

// etc.. 
Aaron
  • 7,055
  • 2
  • 38
  • 53