Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C: convert a NSMutableString in NSString

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

like image 280
cyclingIsBetter Avatar asked Apr 07 '11 15:04

cyclingIsBetter


People also ask

What is NSString In Objective C?

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.

Is NSString UTF 8?

An NSString object can be initialized from or written to a C buffer, an NSData object, or the contents of an NSURL . It can also be encoded and decoded to and from ASCII, UTF–8, UTF–16, UTF–32, or any other string encoding represented by NSStringEncoding .

How do I append to NSString?

Once a string has been initialized using NSString, the only way to append text to the string is to create a new NSString object. While doing so, you can append string constants, NSString objects, and other values.

Do I need to release NSString?

If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it.


2 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.

like image 167
Regexident Avatar answered Sep 22 '22 07:09

Regexident


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]; 
like image 37
Jose Ibanez Avatar answered Sep 22 '22 07:09

Jose Ibanez