views:

165

answers:

2

I have a routine that parses text via a loop. At the end of each record I need to clear my string variables but I read that someString = @"" actually just points to a new string & causes a memory leak.

What is the best way to handle this? Should I rather use mutable string vars and use setString:@"" between iterations?

+1  A: 

You have to be careful in which case you create the NSString: (factory method) or (alloc init or (using @"").

If you use @"", it is a constant string, see here: Constant NSString

If you use [[NSString alloc] init], you need to release it.You just need to do [someString release].

If you use something like [NSString stringWithFormat:@""], you don't need to release it because it is already auto released by runtime

vodkhang
Formatting gets destroyed, hopefully this is legible----------------------------------------------------What about an object declared with the retain property @property (nonatomic, retain) NSString *someString;--------------------------------then assigned a value via copy someString = [parsedCharacters copy];------------------and cleared with a constant string assignment someString = @"";Sorry if my questions seem stupid but something is going a bit wrong here, the retain property should have a corresponding release but the release is causing crashes. What have I messed up?
Spider-Paddy
1st: The property is only used if you use self.someString otherwise, it just a normal assign. Now, you dont' use self. 2nd: if you assign someString to a constant string like @"", you shouldn't release it, please take a look at a link again. Even if you use self.someString = @"", you also shouldn't release it
vodkhang
I think I finally understand this, if I just assign literal strings and use factory methods then the object doesn't need to be released. Even if it is declared with the retain property, is that correct?
Spider-Paddy
With literal strings, that's correct. With factory method, you need to release it when using it retain property
vodkhang
A: 

Since NSStrings are immutable, you cannot change the contents of the string. And by initializing it with @"" you're actually creating a constant NSString object.

You can either work with a NSString local to the loop, and release it in the end of the loop - or you can use a NSMutableString instead. I would prefer the loop local string though.

for ( ; ;) {
    NSString* str = [[NSString alloc] initWithFormat:@"%@", CONTENT];
    ...
    [str release];
}
Björn