How to initialize NSString to NSMutableString?

99封情书 提交于 2019-12-29 06:57:50

问题


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);
}

回答1:


NSString is an immutable representation (or a readonly view at worst). So you would need to either cast to a NSMutableString if you know it's mutable or make a mutable copy:

-(void)st:(NSString *)st
{
  NSMutableString *str =  [[st mutableCopy] autorelease];
  NSLog(@"string: %@", str);
}

I autoreleased it because mutableCopy returns a newly initialized copy with a retain count of 1.




回答2:


NSString *someImmutableString = @"something";
NSMutableString *mutableString = [someImmutableString mutableCopy];

Important! mutableCopy returns an object that you own, so you must either release or autorelease it.




回答3:


You can set an NSMutableString to an NSString, but not the other way around

NSString *str =  [NSMutableString alloc]init];

is okay, but

NSMutableString *str = [[NSString alloc]init];

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

NSMutableString *mStr = [str mutableCopy];



回答4:


Swift 2.0

For Swift users, the following works in Xcode 7.

var str : String = "Regular string"
var mutableStr : NSMutableString = NSMutableString(string: str)


来源:https://stackoverflow.com/questions/1817697/how-to-initialize-nsstring-to-nsmutablestring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!