vince
vince

Reputation: 161

Memory leak NSAutoreleasePool

With instruments i got a memory leak on this piece of code and i don't understand why!

-(void)goToThisUrl:(id) targetUrl
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    if (someCondition) {
        // Doing some stuff here
    }
    // Instruments show memory leak on data
    else {
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString: targetUrl]];
        myTargetImage = [UIImage imageWithData:data];
        // When releasing data(because data retainCount = 2), i got:
        // Incorrect decrement of the reference count of an object that is not owned at this point by the caller
        //[data release];
    }   
    [pool release];
}

Thanks

Upvotes: 0

Views: 323

Answers (2)

MoDJ
MoDJ

Reputation: 4425

First off, you can't allocate a UIImage in a second thread. Uses of UIKit need to be on the main thread. I assume what you wanted to do by creating another thread was to invoke dataWithContentsOfURL without blocking the main thread. But, this is not the right approach. Instead, use a NSURLConnection with an async callback that gets invoked when the download is done. Apple already provides a built-in "download" thread that NSURLConnection uses behind the scenes. So, your approach of creating another thread to download is pointless.

Upvotes: 0

Sherm Pendley
Sherm Pendley

Reputation: 13612

There is no leak in the above. There may be one or more leaks in the parts you've deleted and replaced with "someCondition" and "Doing some stuff here," but no one here can help with that unless you post the complete code that you're really testing with Instruments.

Also: "// When releasing data(because data retainCount = 2) ..." Stop. Right. There. Ignore retainCount. You release an object because you've created it using a method that implies ownership, or because you've retained it. You NEVER release an object just because its retainCount has a value you didn't expect or don't understand. Read Apple's Memory Management Programming Guide for details.

Upvotes: 3

Related Questions