HardCode
HardCode

Reputation: 99

iPhone Memory leak

I get Potential leak of an object allocated on line 55 and stored into 'returnURL' Memory leak error.

My Code

NSString *returnURL = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
return returnURL;
[returnURL release];

Please help

Upvotes: 0

Views: 455

Answers (2)

Ben Zotto
Ben Zotto

Reputation: 71058

You should "autorelease" this NSString before returning it:

NSString *returnURL = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
return [returnURL autorelease];

Or the pattern many use is to simply autorelease at the site of the alloc:

NSString *returnURL = [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding] autorelease];

This basically means you're saying you don't want to hold the reference, but you want it to remain "alive" for the rest of the event loop so you can pass it back to the caller of your method, who can then use it without worrying about ownership.

Upvotes: 3

albertamg
albertamg

Reputation: 28572

Any statements after the return are not executed. Hence, returnURL is never released. And you don't want to release it before you return because you want to give the caller an opportunity to retain the object. In fact, this is the classical example of autorelease:

return [returnURL autorelease];

Upvotes: 7

Related Questions