7

Is there any way to initialize NSString to NSMutableString? and also reverse order?

-(void)st:(NSString *)st
{
  NSMutableString str = st; // gives warning..
  NSLog(@"string: %@", str);
}
HangarRash
  • 7,314
  • 5
  • 5
  • 32

4 Answers4

11

NSString is an immutable representation (or a readonly view at worst). So you would need to either cast to a NSMutableString if you know it's mutable or make a mutable copy:

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

I autoreleased it because mutableCopy returns a newly initialized copy with a retain count of 1.

notnoop
  • 58,763
  • 21
  • 123
  • 144
  • I don't know if this will work how it is, but the NSMutableString should be a pointer NSMutableString *str = [[st mutableCopy] autorelease]; – Joe Cannatti Nov 30 '09 at 14:49
4

You can set an NSMutableString to an NSString, but not the other way around

NSString *str =  [NSMutableString alloc]init];

is okay, but

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

is not. This is because an NSMutableString is a subclass of NSString, so it 'is a' NSString. You can however create a mutable string from an NSString with

NSMutableString *mStr = [str mutableCopy];
Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
Joe Cannatti
  • 4,989
  • 5
  • 38
  • 56
4
NSString *someImmutableString = @"something";
NSMutableString *mutableString = [someImmutableString mutableCopy];

Important! mutableCopy returns an object that you own, so you must either release or autorelease it.

Bryan Henry
  • 8,348
  • 3
  • 34
  • 30
1

Swift 2.0

For Swift users, the following works in Xcode 7.

var str : String = "Regular string"
var mutableStr : NSMutableString = NSMutableString(string: str)
Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135