Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize NSString to NSMutableString?

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);
}
like image 329
senthilM Avatar asked Nov 30 '09 03:11

senthilM


2 Answers

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.

like image 103
notnoop Avatar answered Sep 23 '22 06:09

notnoop


NSString *someImmutableString = @"something";
NSMutableString *mutableString = [someImmutableString mutableCopy];

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

like image 27
Bryan Henry Avatar answered Sep 22 '22 06:09

Bryan Henry