2010-11-30 114 views
3

爲什麼會泄漏?這個Objective-C代碼爲什麼會泄漏內存?

arrayOfPerformances是合成的NSMutableArray,(nonatomic, retain)屬性。

currentPerformanceObjectPerformance *,(nonatomic, retain)合成的屬性。

Performance是一個自定義類

if(self.arrayOfPerformances == nil) 
    { 
     self.arrayOfPerformances = [[NSMutableArray alloc]init]; 
    } 

    [self.arrayOfPerformances addObject:currentPerformanceObject]; 
    [currentPerformanceObject release]; 
    currentPerformanceObject = nil; 

回答

11

您正在創建一個新的數組在這條線的同時保留它,因爲你調用與點號一個(retain)的屬性設置:

// Your property 
@property (nonatomic, retain) NSMutableArray *arrayOfPerformances; 

// The offending code 
self.arrayOfPerformances = [[NSMutableArray alloc]init]; 

因此,本地創建的陣列泄漏,因爲您不釋放它。你應該自動釋放該數組,或者創建一個臨時局部變量,分配,然後釋放局部變量,就像這樣:

// Either this 
self.arrayOfPerformances = [[[NSMutableArray alloc] init] autorelease]; 

// Or this (props Nick Forge, does the same as above) 
self.arrayOfPerformances = [NSMutableArray array]; 

// Or this 
NSMutableArray *newArray = [[NSMutableArray alloc] init]; 
self.arrayOfPerformances = newArray; 
[newArray release]; 
+1

尼克說什麼;使用`[NSMutableArray數組]` – bbum 2010-11-30 03:36:00

+0

哇,那個制定者真的搞砸了我的想法。我梳理了我的代碼幾個小時,試圖找出泄漏的位置,並最終隔離了代碼,並且無法弄清楚我的生活出了什麼問題。太感謝了! – Mausimo 2010-11-30 03:41:30

4

如果您.arrayOfPerformances物業從來沒有公佈過(它通常會在-dealloc公佈),比數組本身,加上數組中的任何對象都會在處理這個對象時泄漏。

你需要在你-dealloc釋放兩個屬性:

- (void)dealloc 
{ 
    ... other deallocs 
    self.arrayOfPerformances = nil; 
    self.currentPerformanceObject = nil; 
    [super dealloc]; 
} 

此外,作爲@BoltClock已經指出的那樣,你需要釋放或自動釋放你的NSMutableArray。要做到這一點,最好的辦法就是使用自動釋放的方法來初始化它:

self.arrayOfPerformances = [NSMutableArray array]; 

而且,你不需要釋放你currentPerformanceObject,你應該只設置屬性爲nil,因爲retain編輯屬性設置爲nil會爲您發佈。您的代碼可能應該是這個樣子:

if (self.arrayOfPerformances == nil) { 
    self.arrayOfPerformances = [NSMutableArray array]; 
} 
[self.arrayOfPerformances addObject:self.currentPerformanceObject]; 
self.currentPerformanceObject = nil; 
1

此行是罪魁禍首:

self.arrayOfPerformances = [[NSMutableArray alloc]init]; 

保留計數爲1的分配/初始化後。通過arrayOfPerformances屬性設置器設置值會再次增加保留計數(因爲它是一個保留屬性)。