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
This is definitely a leak. The easiest way to take care of issues like this is to autorelease sooner rather than later:
You could also use NSMutableString to do this as well, in place (if this isn’t a notional example).