views:

342

answers:

2

I have a simple function that returns an NSString after decoding it. I use it a lot throughout my application, and it appears to create a memory leak (according to "leaks" tool) every time I use it. Leaks tells me the problem is on the line where I alloc the NSString that I am going to return, even though I autorelease it. Here is the function:

-(NSString *) decodeValue
{
 NSString *newString;
 newString = [self stringByReplacingOccurrencesOfString:@"#" withString:@"$"];
 NSData *stateData = [NSData  dataWithBase64EncodedString:newString];
 NSString *convertState = [[[NSString alloc] initWithData:stateData encoding:NSUTF8StringEncoding] autorelease];
 return convertState;
}

My understanding of [autorelease] is that it should be used in exactly this way... where I want to hold onto the object just long enough to return it in my function and then let the object be autoreleased later. So I believe I can use this function through code like this without manually releasing anything:

NSString *myDecodedString = [myString decodeValue];  

But this process is reporting leaks and I don't understand how to change it to avoid the leaks. What am I doing wrong?

+3  A: 

I think leaks is leading you astray. Leaks will tell you where the object being leaked was originally allocated, not necessarily the same as the reason for the leak. This code seems fine - what's probably happening is that this result is being retained in another class somewhere and never released there.

jexe
OK, thank you. So if I'm understanding you and starkhalo correctly, what leaks is telling me is that the object is alloc'd in my function and even though it is set to autorelease, it is somehow being retained by whatever code is invoking this function call somewhere. Is that a reasonable interpretation of what you are saying?
hookjd
Yep! Exactly. Check whatever code calls this and be sure that it's releasing the return value, if it retains it.
jexe
A: 

Jexe is right, the Leaks tool cannot possibly know where the leak is, all it knows is the point of creation of an instance and that at the end of the RunLoop said object still was being retained, that's why it's pointing to the alloc call. It's still a big help, now you just have to figure out who else is having access to convertState and retaining it.