2011-08-29 83 views
0

Xcode是報告上的代碼中的特定行中的內存泄漏:的NSMutableArray存儲器泄漏

(NSArray*)myFunction{ 
    NSMutableArray * tempMapListings=[[NSMutableArray alloc] init]; //Xcode says leak is here 

    //do a bunch of stuff to insert objects into this mutable array 


    return tempMapListings; 
    [tempMapListings release]; // but I release it ?! 

    } 

這是由於釋放作爲一個NSArray一個可變數組?由於mutable從無法繼承,我不認爲這是一個問題,並且無論如何,該對象被釋放。我會很感激第二隻眼睛的建議。

+2

「這是因爲NSArray是一個可變數組嗎?」 - 你是什麼意思?問題不在這裏,而是與該功能有關。你可以發佈所有使用該功能的代碼嗎?你能不能準確地展示你對這個陣列做了什麼? – darksky

回答

3

您正在發佈tempMapListings之後您從函數返回。在返回語句之後,在該分支上不再執行任何代碼。 Ergo,你的[tempListListings release]聲明永遠不會運行。而且,當你回來的時候,你並不想馬上釋放它 - 呼叫者永遠不會有機會保留這個數組!

Autorelease池是你的朋友在這裏。添加到自動釋放池的對象最終會以您的名義發佈,讓您的呼叫者有時間獲取結果。爲了您的對象添加到默認池,你的配置行更改爲

NSMutableArray *tempMapListings = [[[NSMutableArray alloc] init] autorelease]; 

,並刪除最後release電話。

有關autorelease池的更多信息,請閱讀Apple's documentation。他們真的很有用。

+0

謝謝!我知道這將是明顯的。 – johnbakers

5

不,你不釋放它。 return聲明確實結束了該方法的執行。因此,它下面的線,你的情況

[tempMapListings release]; // but I release it ?! 

不執行

而是使用autorelease

-(NSArray*)myFunction{ 
    NSMutableArray * tempMapListings=[[NSMutableArray alloc] init]; 
    //do a bunch of stuff to insert objects into this mutable array 
    return [tempMapListings autorelease]; 
} 

你可以學到很多地方約autorelease。在Apple自己的文檔中查找它;你也可以谷歌它。