Goal C: Convert NSMutableString to NSString

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

+56
objective-c nsstring nsmutablestring
Apr 7 2018-11-11T00:
source share
2 answers

Or through:

NSString *immutableString = [NSString stringWithString:yourMutableString]; 

or through:

 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, you can just pass it to NSString

 NSString *immutableString = yourMutableString; 

which makes it unchanged, although in reality it remains volatile.
Many methods actually return mutable instances, even though they are declared to return immutable.

+88
Apr 07 2018-11-11T00:
source share

NSMutableString is a subclass of NSString , so you can just give it:

 NSString *string = (NSString *)mutableString; 

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

Alternatively, you can create a new NSString using the class method:

 NSString *string = [NSString stringWithString:mutableString]; 
+3
Apr 07 2018-11-11T00:
source share



All Articles