Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating NSStrings in Objective C

How do I concatenate to NSStrings together in Objective C?

like image 363
arachide Avatar asked Feb 10 '10 01:02

arachide


People also ask

How do you concatenate strings in Objective C?

First, use an NSMutableString , which has an appendString method, removing some of the need for extra temp strings. Second, use an NSArray to concatenate via the componentsJoinedByString method.

What is NSString?

A static, plain-text Unicode string object which you use when you need reference semantics or other Foundation-specific behavior.


1 Answers

If the string is not mutable, you will instead want:

NSString *firstString = @"FirstString";
NSString *secondString = @"SecondString";
NSString *concatinatedString = [firstString stringByAppendingString:secondString];
// Note that concatinatedString is autoreleased, 
// so if you may want to [concaticatedString retain] it.

For completeness, here's the answer for a mutable string:

NSMutableString *firstString = [NSMutableString stringWithString:@"FirstString"];
NSString *secondString = @"SecondString";
[firstString appendString:secondString];
// Note that firstString is autoreleased, 
// so if you may want to [firstString retain] it.
like image 106
Lawrence Johnston Avatar answered Sep 21 '22 13:09

Lawrence Johnston