stringByAppendingFormat not working

2019-04-19 10:51发布

问题:

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.

回答1:

I would suggest correcting to (documentation):

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

From the docs:

Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments.



回答2:

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.



回答3:

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];


回答4:

I had a similar warning message while appending a localized string. This is how I resolved it

NSString *msgBody = [msgBody stringByAppendingFormat:@"%@",NSLocalizedString(@"LOCALSTRINGMSG",@"Message Body")];