Objective C: convert a NSMutableString in NSString

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

Answers


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.


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];

Need Your Help

React - Check If Props Exist

javascript reactjs

I searched around the internet for an answer to this question, and I didn't find one. Therefore I am posting my question here.

Why aren't static methods considered good OO practice?

java scala oop static-methods language-concepts

I'm reading Programming Scala. At the beginning of chapter 4, the author comments that Java supports static methods, which are "not-so-pure OO concepts." Why is this so?