views:

777

answers:

3

I have an NSString and fail to apply the following statement:

NSString *myString = @"some text";
[myString stringByAppendingFormat:@"some text = %d", 3];

no log or error, the string just doesn't get changed. I already tried with NSString (as documented) and NSMutableString.

any clues most welcome.

+7  A: 

I would suggest correcting to:

NSString *myString = @"some text";
myString = [myString stringByAppendingFormat:@" = %d", 3];
Paul Lynch
+5  A: 

Creating strings with @"" always results in immutable strings. If you want to create a new NSMutableString do it as following.

NSMutableString *myString = [NSMutableString stringWithString:@"some text"];
[myString appendFormat:@"some text = %d", 3];
stigi
+3  A: 

It's working, you're just ignoring the return value, which is the string with the appended format. (See the docs.) You can't modify an NSString — to modify an NSMutableString, use -appendFormat: instead.

Of course, in your toy example, you could shorten it to this:

NSString *myString = [NSString stringWithFormat:@"some text = %d", 3];

However, it's likely that you need to append a format string to an existing string created elsewhere. In that case, and particularly if you're appending multiple parts, it's good to think about and balance the pros and cons of using a mutable string or several immutable, autoreleased strings.

Quinn Taylor