Search code examples
iphoneobjective-cnsstringnsmutablestring

NSMutableString Append Fails


I have an NSString that I'd like to append a { at the beginning of it.

 NSMutableString *str = [[NSMutableString alloc] initWithString:@"{"];
    [str stringByAppendingString:extracted];

This returns str with only {. Why is that? Objective-C is VERY frustrating with how it provides many ways of doing the same thing, yet for situations a different way is required.

I tried doing [NSMutableString string] and appending { then extracted and it still does not work. Why is this not working and what should I do?


Solution

  • stringByAppendingString returns a new string, it does not modify the old string.

    All functions that begins with stringWith or arrayWith etc. create new objects rather than modifying old objects.

    To acheive what you want, a simpler solution is:

     NSString *str = [NSString stringWithFormat:@"{%@", oldString];
    

    or:

     NSMutableString *str = [@"{" mutableCopy];
     [str appendString:blah];