How to initialize NSString for NSMutableString?

Is there a way to initialize an NSString for an NSMutableString? as well as the reverse order?

-(void)st:(NSString *)st { NSMutableString str = st; // gives warning.. NSLog(@"string: %@", str); } 
+6
casting objective-c iphone nsmutablestring
source share
4 answers

NSString is an immutable view (or, in the worst case, readonly view). Thus, you will need to either switch to NSMutableString if you know that it is modified or make a mutable copy:

 -(void)st:(NSString *)st { NSMutableString *str = [[st mutableCopy] autorelease]; NSLog(@"string: %@", str); } 

I will implement it because mutableCopy returns a new initialized copy, keeping the number at 1.

+10
source share

You can set NSMutableString to NSString, but not vice versa.

 NSString *str = [NSMutableString alloc]init]; 

ok but

 NSMutableString *str = [[NSString alloc]init]; 

not. This is because NSMutableString is a subclass of NSString, so it is an "NSString". However, you can create a mutable string from NSString with

 NSMutableString *mStr = [str mutableCopy]; 
+4
source share
 NSString *someImmutableString = @"something"; NSMutableString *mutableString = [someImmutableString mutableCopy]; 

Important! mutableCopy returns the object you have, so you must either free it or auto-update it.

+3
source share

Swift 2.0

For Swift users, the following works in Xcode 7.

 var str : String = "Regular string" var mutableStr : NSMutableString = NSMutableString(string: str) 
+1
source share

All Articles