Reputation: 925
I am relatively new in Objective C but not with programming. I was wondering how you can append one NSString onto another. I am making an app in which a user has to finish a basic sentence, and I was wondering how to get the string the user entered and append it onto the current one that is on the screen?
Upvotes: 29
Views: 54903
Reputation: 1305
This could also be achieved by using a NSMutableString:
NSMutableString *string = [NSMutableString stringWithString:@"String 1"];
[string appendString:@"String 2"];
Upvotes: 42
Reputation: 1795
You cannot truly append one NSString to another because the class NSString is not mutable. All of the standard data structures have mutable and non mutable varieties (NSMutableString vs NSString, NSMutableArray vs NSArray, etc). If you want to change the contents without reallocating a new object, you will want to use the mutable version. You can recreate a new NSString using:
NSString* string3 = [NSString stringWithFormat:@"%@%@",string1,string2];
This is bad for performance though, so if you are going to do it in a loop or some performance sensitive area (i.e. you keep appending to the same string over and over again) this is guaranteed to cause you a problem (I have made this mistake before).
Instead you probably should use the NSMutableString and append the second string to it:
NSMutableString* string1 = [NSMutableString alloc] init];
[string1 appendString:string2];
Upvotes: 6
Reputation: 1333
It looks like you have your answer but you can also use the stringWithFormat:
method like so:
NSString *sample1 = @"Hello";
NSString *sample2 = @"Being appended";
NSString *complete = [NSString stringWithFormat:@"%@%@", sample1,
sample2];
Upvotes: 14
Reputation: 1694
I think you are looking for stringByAppendingString function of NSString. See the example below.
NSString *errorTag = @"Error: ";
NSString *errorString = @"premature end of file.";
NSString *errorMessage = [errorTag stringByAppendingString:errorString];
produces the string “Error: premature end of file.”.
Upvotes: 50