views:

195

answers:

1

Suppose I have a variable that's already been initialized to a string via an alloc/init combination. Will I have memory leakage if I reassign it via processing, ie.

NSString *s = [[NSString alloc] initWithString:someOtherStringVariable];
s = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Has there been memory leakage here? If so, do I need to create another variable (e.g. s2), do this assignment, and then release the original?

NSString *s = [[NSString alloc] initWithString:someOtherStringVariable];
NSString *s2 = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[s release];

Now, what if the some other string is a constant, like @"Some other string". Would I need to worry about leakage? ie.

NSString *s = [[NSString alloc] initWithString:@"Some other string"];
s = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Thanks

+7  A: 

This is definitely a leak. The easiest way to take care of issues like this is to autorelease sooner rather than later:

NSString *s = [[[NSString alloc] initWithString:@"Some other string"] autorelease];
s = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

You could also use NSMutableString to do this as well, in place (if this isn't a notional example).

sbooth
Thanks. The example was notional as you point out. I thought I had read somewhere that there is memory allocated for the string literal in any case, so it would never be released. So it's retain count was irrelevant.
LeftHem
It's true that you don't have to release/manually memory-manage string literals. However, in your code you don't assign a string literal directly, but rather do [NSString alloc] before. As soon as you have an alloc you need an (auto)release. This won't leak: NSString* s = @"Some string"; s = [...];
Daniel Rinser
Got it. Thanks.
LeftHem