如何将 NSString 初始化为 NSMutableString?
有什么方法可以将 NSString 初始化为 NSMutableString 吗?并且还颠倒顺序?
-(void)st:(NSString *)st
{
NSMutableString str = st; // gives warning..
NSLog(@"string: %@", str);
}
Is there any way to initialize NSString to NSMutableString? and also reverse order?
-(void)st:(NSString *)st
{
NSMutableString str = st; // gives warning..
NSLog(@"string: %@", str);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
NSString
是一个不可变的表示(或者最坏的情况下是一个只读视图)。因此,如果您知道它是可变的,则需要转换为 NSMutableString 或创建一个可变副本:我自动释放了它,因为 mutableCopy 返回一个新初始化的副本,其保留计数为1.
NSString
is an immutable representation (or a readonly view at worst). So you would need to either cast to aNSMutableString
if you know it's mutable or make a mutable copy:I autoreleased it because
mutableCopy
returns a newly initialized copy with a retain count of 1.重要!
mutableCopy
返回一个您拥有的对象,因此您必须释放或自动释放它。Important!
mutableCopy
returns an object that you own, so you must either release or autorelease it.你可以将 NSMutableString 设置为 NSString,但反过来也
可以,但
不行。这是因为 NSMutableString 是 NSString 的子类,因此它“是”NSString。
但是,您可以使用 NSString 创建可变字符串
You can set an NSMutableString to an NSString, but not the other way around
is okay, but
is not. This is because an NSMutableString is a subclass of NSString, so it 'is a' NSString.
You can however create a mutable string from an NSString with
Swift 2.0
对于 Swift 用户,以下内容适用于 Xcode 7。
Swift 2.0
For Swift users, the following works in Xcode 7.