views:

205

answers:

1

I have a calling method that looks like the following:

-(void)callingMethod
{
     NSMutableString *myStr = [[[NSMutableString alloc] initWithCapacity:0] autorelease];
     myStr = [self calledMethod];
}

And my called method:

-(NSMutableString*)calledMethod
{
    NSMutableString *newStr = [[NSMutableString alloc] initWithCapacity:0];
    // do some stuff with newStr
    return [newStr autorelease];
}

Am I leaking memory anywhere here? I feel like I'm allocing an unnecessary amount here.

+6  A: 

No, you're not leaking memory, but your instinct that you are allocing an unnecessary amount here is correct.

At a minimum, you should consider rewriting the callingMethod as:

- (void)callingMethod
{
    NSMutableString *myStr = [self calledMethod];
}

You can also tidy up the calledMethod as:

- (NSMutableString*)calledMethod
{
    return [NSMutableString stringWithCapacity:0]; // why 0 capacity?
}
Jarret Hardie
HAHAHAHA... thanks for the edit Jason. Monkey see void, monkey copy void :-)
Jarret Hardie
He is not releasing myStr in callingMethod. Is that not a memory leak ?
euphoria83
Good question... no, it's not since myStr is autoreleased because it was created using the [NSMutableString stringWithCapacity] call (as opposed to with [[NSMutableString alloc] init])
Jarret Hardie
@euphoria: he doesn't have to... he doesn't own it. If he wants to use it outside the scope of callingMethod he'll have to take ownership of it by retaining it or copying it. At that point, he will have to release it at some later point to avoid a memory leak.
Jason Coco
And in his original example, it was deliberately autoreleased, so no worries there either.
Jarret Hardie
Thanks all, I understand better now.
Coocoo4Cocoa
So silly of me. I missed the autorelease since it was on the scrolled out portion. @Jason :But now I am confused by your comment. Anything created with an alloc and init is owned by the user, right ? Or is it that the message "autorelease" makes the user lose ownership of the variable ?
euphoria83
Yeah, autorelease is like release in that you're giving up ownership of the object, the obvious difference between the two is that release immediately decrements the reference count while autorelease does at some point in the future.
Jason Coco