0

使用仪器时,我在这段代码上出现了内存泄漏,我不明白为什么!

-(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];
}

谢谢

4

2 回答 2

3

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.

于 2011-04-23T23:39:51.693 回答
0

首先,您不能在第二个线程中分配 UIImage。UIKit 的使用需要在主线程上。我假设您想通过创建另一个线程来调用 dataWithContentsOfURL 而不会阻塞主线程。但是,这不是正确的方法。相反,使用带有异步回调的 NSURLConnection,下载完成时会调用该回调。Apple 已经提供了 NSURLConnection 在幕后使用的内置“下载”线程。因此,您创建另一个下载线程的方法毫无意义。

于 2011-05-27T15:48:57.533 回答