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:
- Use whichever one makes your code clear and easy to read.
- When your app is working correctly, use Instruments to profile it.
- Only if you find out that string concatenation is causing a performance problem, consider a different method.