开发者

Memory leak NSAutoreleasePool

开发者 https://www.devze.com 2023-02-28 12:08 出处:网络
With instruments i got a memory leak on this piece of code and i don\'t understand why! -(void)goToThisUrl:(id) targetUrl

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号