开发者

stringByAppendingFormat not working

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 开发者_StackOverflow中文版documented) and NSMutableString.

any clues most welcome.


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.


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.


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


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")];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜