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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With