0

Is there a better way to achieve concatenating multiple strings in one single line? Or any advise at all when doing this.

NSString *string1 = @"one";
NSString *string2 = @"one";
NSString *string3 = @"one";
NSString *appendedText = @"";

[appendedText = [[string1 stringByAppendingString: string2] stringByAppendingString: string3]
stackdaddy
  • 111
  • 1
  • 10

2 Answers2

1

Safe and proper? Sure.

Let's say you have:

NSString *a = @"hay";
NSString *b = @"bee";
NSString *c = @"see";

You can use stringByAppendingString: to concatenate them all:

cat = [a stringByAppendingString:[b stringByAppendingString:c]];

You can use stringByAppendingFormat: to concatenate them all:

cat = [a stringByAppendingFormat:@"%@%@", b, c];

You can use stringWithFormat::

cat = [NSString stringWithFormat:@"%@%@%@", a, b, c];

You can put them in an array, and use componentsJoinedByString:: (just for fun, using array literal syntax)

array = @[ a, b, c];
cat = [array componentsJoinedByString:@""];

You can collect them in a mutable string:

NSMutableString *temp = [a mutableCopy];
[temp appendString:b];
[temp appendString:b];
cat = [temp copy]; // if you want to make sure result is immutable

All of these methods are OK. Here's my advice for choosing one to use:

  1. Use whichever one makes your code clear and easy to read.
  2. When your app is working correctly, use Instruments to profile it.
  3. Only if you find out that string concatenation is causing a performance problem, consider a different method.
Community
  • 1
  • 1
benzado
  • 82,288
  • 22
  • 110
  • 138
0

You can use stringByAppendingFormat:

[string1 stringByAppendingFormat:@"%@%@",string2,string3]

Here is a ref

you also have NSMutableString but in terms of syntax it will look about the same

Daniel

Daniel
  • 22,363
  • 9
  • 64
  • 71
  • I had forgot all about NSMutableString thanks for reminding me. I will take this into consideration with future apps because I think it may be more clear. – stackdaddy Aug 24 '12 at 18:26