I have an NSMutableString, how can I convert it to an NSString?
(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.
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 .
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.
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With