stringByAppendingFormat not working

2019-04-19 10:34发布

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.

4条回答
Animai°情兽
2楼-- · 2019-04-19 11:15

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")];
查看更多
小情绪 Triste *
3楼-- · 2019-04-19 11:25

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楼-- · 2019-04-19 11:26

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.

查看更多
萌系小妹纸
5楼-- · 2019-04-19 11:31

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.

查看更多
登录 后发表回答