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.
From stackoverflow
-
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
callingMethodas:- (void)callingMethod { NSMutableString *myStr = [self calledMethod]; }You can also tidy up the
calledMethodas:- (NSMutableString*)calledMethod { return [NSMutableString stringWithCapacity:0]; // why 0 capacity? }Jarret Hardie : HAHAHAHA... thanks for the edit Jason. Monkey see void, monkey copy void :-)euphoria83 : He is not releasing myStr in callingMethod. Is that not a memory leak ?Jarret Hardie : 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])Jason Coco : @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.Jarret Hardie : And in his original example, it was deliberately autoreleased, so no worries there either.Coocoo4Cocoa : Thanks all, I understand better now.euphoria83 : 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 ?Jason Coco : 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.
0 comments:
Post a Comment