Coming from a .NET background I’m use to reusing string variables for storage, so is the code below likely to cause a memory leak? The code is targeting the iphone/itouch so no automatic GC.
-(NSString*) stringExample
{
NSString *result = @"example";
result = [result stringByAppendingString:@" test"]; // where does "example" go?
return result;
}
What confuses me is NSStrings are immutable, but you can reuse an ‘immutable’ variable with no problem.
It definitely can result in memory leaks. You have to be careful about reusing in that you have to know a lot about the actual implementation of the underlying NSString object to decide if you’re “safe” or not. So, if you’re not using garbage collection, to be safe, you should not reuse variables the way you have.
For example, this is totally safe:
because the initial string was actually an objective-c string constant. This, however, would result in a memory leak:
This, however, would be safe since you never owned result in the first place:
So basically, if you don’t own the object or you have garbage collection turned on, it is safe. If, however, you own the original object and you do this, you will be leaking memory.