Objective C: convert a NSMutableString in NSString

混江龙づ霸主 提交于 2019-12-03 06:27:57

问题


I have an NSMutableString, how can I convert it to an NSString?


回答1:


Either via:

NSString *immutableString = [NSString stringWithString:yourMutableString];

or via:

NSString *immutableString = [[yourMutableString copy] autorelease];
//Note that calling [foo copy] on a mutable object of which there exists an immutable variant
//such as NSMutableString, NSMutableArray, NSMutableDictionary from the Foundation framework
//is expected to return an immutable copy. For a mutable copy call [foo mutableCopy] instead.

Being a subclass of NSString however you can just cast it to an NSString

NSString *immutableString = yourMutableString;

making it appear immutable, even though it in fact stays mutable.
Many methods actually return mutable instances despite being declared to return immutable ones.




回答2:


NSMutableString is a subclass of NSString, so you could just typecast it:

NSString *string = (NSString *)mutableString;

In this case, string would be an alias of mutalbeString, but the compiler would complain if you tried to call any mutable methods on it.

Also, you could create a new NSString with the class method:

NSString *string = [NSString stringWithString:mutableString];


来源:https://stackoverflow.com/questions/5583510/objective-c-convert-a-nsmutablestring-in-nsstring

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