stringByAppendingFormat 不起作用
我有一个 NSString 并且无法应用以下语句:
NSString *myString = @"some text";
[myString stringByAppendingFormat:@"some text = %d", 3];
没有日志或错误,字符串只是没有更改。我已经尝试过 NSString (如文档所述)和 NSMutableString。
欢迎任何线索。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议更正为 (文档):
来自文档:
I would suggest correcting to (documentation):
From the docs:
它正在工作,您只是忽略返回值,它是带有附加格式的字符串。 (参见文档。)您无法修改 NSString — 要修改 NSMutableString,请使用 -appendFormat: 代替。
当然,在您的玩具示例中,您可以将其缩短为:
但是,您可能需要将格式字符串附加到其他地方创建的现有字符串中。在这种情况下,特别是如果您要附加多个部分,最好考虑并平衡使用可变字符串或多个不可变的自动释放字符串的利弊。
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:
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.
使用
@""
创建字符串始终会产生不可变的字符串。如果你想创建一个新的 NSMutableString ,请按以下步骤操作。Creating strings with
@""
always results in immutable strings. If you want to create a new NSMutableString do it as following.我在附加本地化字符串时收到类似的警告消息。我就是这样解决的
I had a similar warning message while appending a localized string. This is how I resolved it