2

I have an NSMutableString called makeString. I want to create it at the beginning of my program without having to set its text. I then want to be able to set its text. I am currently using the following to create it.

NSMutableString *make2String = [[NSMutableString alloc] initWithString:@""];

I am then using the following to set its text value.

make2String = [NSString stringWithFormat:@"Gold.png"];

Is this ok to do or is there a better way to set an NSMutableString's text?

jscs
  • 63,694
  • 13
  • 151
  • 195
Blane Townsend
  • 2,888
  • 5
  • 41
  • 55
  • Can you make your question a question? i.e. "Is this ok to do or is there a better way to set an NSMutableString's text**?**" – Ken May 30 '11 at 01:44
  • Since you seem to be using a string to hold a filename you might find using `NSString` preferable. – Ken May 30 '11 at 03:43

3 Answers3

4

That is not ok, you are replacing your mutable string with an ordinary immutable string (and leaking the original mutable string in the process). You could do [NSMutableString stringWithFormat:@"Gold.png"] after releasing the old string if you wanted to go that route. Or you could use NSMutableString's setString: method to set the content.

But if you're not actually mutating the string and just assigning different strings, you don't need NSMutableString at all. Just do make2String = @"Gold.png"; and be done with it.

Anomie
  • 92,546
  • 13
  • 126
  • 145
1
  NSMutableString * aString = [NSMutableString alloc];
  aString = [aString init];
  [aString setString:@"yourText"];
  [aString setString:@"yourNewText"];
  [aString setString:@"yourNewNewText"];
  //...
  [aString release];
Ken
  • 30,811
  • 34
  • 116
  • 155
0

make2String = [NSMutableString stringWithFormat:@"Gold.png"];

FYI: This is how I allocate NSMutableStrings without setting text

NSMutableString *string = [[NSMutableString alloc] init];

CGTheLegend
  • 734
  • 1
  • 7
  • 19