2011-04-23 86 views
0

隨着儀器我得到了這段代碼的內存泄漏,我不明白爲什麼!內存泄漏NSAutoreleasePool

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

由於

+0

你正在爲分離的線程做這件事,對吧? – 2011-04-23 11:37:41

+0

是的,這就是爲什麼我分配一個NSAutoreleasePool到這個方法:) – vince 2011-04-23 12:45:19

回答

3

有一個在上方沒有泄漏。有可能是您刪除的部分中的一處或多處泄漏,並以「someCondition」和「在此處做某些事情」取代,但這裏沒有人可以幫助解決這個問題,除非您發佈代碼爲完整真正用儀器進行測試。

此外:「//釋放數據時(因爲數據retainCount = 2)...」停止。對。那裏。忽略retainCount。你釋放一個對象,因爲你已經使用隱含所有權的方法創建它,或者因爲你保留了它。你永遠不會只是因爲它的retainCount有一個你沒有料到或不明白的值而釋放一個對象。有關詳細信息,請閱讀Apple的Memory Management Programming Guide

0

首先,您不能在第二個線程中分配UIImage。 UIKit的使用需要在主線程上。我假設你想通過創建另一個線程來執行的操作是在不阻塞主線程的情況下調用dataWithContentsOfURL。但是,這不是正確的做法。相反,使用帶有異步回調的NSURLConnection,在下載完成時調用該異步回調。 Apple已經提供了NSURLConnection在幕後使用的內置「下載」線程。所以,你創建另一個線程下載的方法是毫無意義的。