I've got a rather large loop that gets a string, does something to it, than goes onto the next one. I was originally releasing it then reallocating it but thought that is a bit of waste of resources but can't figure out how to just clear it out to reuse it.
Asked
Active
Viewed 7,996 times
2 Answers
22
One way would be [myString setString: @""]
.

JWWalker
- 22,385
- 6
- 55
- 76
-
1Thats annoying, I actually tried that and it crashed so thought it wouldn't work. Ended up I left another statement which crashed it. – Rudiger Jul 26 '10 at 22:22
1
The selected solution will crash with the following error:
'Attempt to mutate immutable object with setString:'
This worked for me instead:
self.myString = [NSMutableString stringWithString:@""];
make sure you synthesize myString in your class.

MyCSharpCorner
- 1,313
- 11
- 15
-
Agreed. Setting an NSMutableString to an NSString is not good. The error you get in Xcode 4.4 is "Incompatible pointer types sending 'NSString *' to parameter of type 'NSMutableString *'". Setting it with this solution is better. – Joseph Sep 09 '12 at 00:50
-
1It seems to me that this is allocating a new NSMutableString instance? Is that not just as much a waste of resources as in the original question? – ArtOfWarfare Apr 11 '13 at 12:30
-
If you get 'Attempt to mutate immutable object with setString:' then the string you're trying to modify is not an `NSMutableString`, and you're dealing with a different problem than "Clearing rather than releasing a NSMutableString", the title of this question. – JWWalker Sep 11 '13 at 17:23