[英]Why is this Objective-C code leaking memory?
為什么泄漏?
arrayOfPerformances
是一個NSMutableArray
, (nonatomic, retain)
屬性,它是合成的。
currentPerformanceObject
是一個合成的Performance *
, (nonatomic, retain)
屬性。
Performance
是一個自定義類
if(self.arrayOfPerformances == nil)
{
self.arrayOfPerformances = [[NSMutableArray alloc]init];
}
[self.arrayOfPerformances addObject:currentPerformanceObject];
[currentPerformanceObject release];
currentPerformanceObject = nil;
您正在創建一個新數組並在此行中同時保留它,因為您使用點表示法調用(retain)
屬性設置器:
// Your property
@property (nonatomic, retain) NSMutableArray *arrayOfPerformances;
// The offending code
self.arrayOfPerformances = [[NSMutableArray alloc]init];
因此,本地創建的數組正在泄漏,因為您沒有釋放它。 您應該自動釋放該數組,或者創建一個臨時的本地var,賦值,然后釋放本地var,如下所示:
// 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];
如果你的.arrayOfPerformances
屬性從未被釋放(它通常會在-dealloc
釋放),那么除了數組本身之外,當釋放此對象時,數組中的任何對象都將被泄露。
您需要在-dealloc
釋放這兩個屬性:
- (void)dealloc
{
... other deallocs
self.arrayOfPerformances = nil;
self.currentPerformanceObject = nil;
[super dealloc];
}
此外,正如@BoltClock指出的那樣,您需要釋放或自動釋放您的NSMutableArray
。 最好的方法是使用自動釋放的方法初始化它:
self.arrayOfPerformances = [NSMutableArray array];
此外,您不需要釋放currentPerformanceObject
,您應該將該屬性設置為nil,因為將retain
ed屬性設置為nil
將為您釋放它。 您的代碼應該看起來像這樣:
if (self.arrayOfPerformances == nil) {
self.arrayOfPerformances = [NSMutableArray array];
}
[self.arrayOfPerformances addObject:self.currentPerformanceObject];
self.currentPerformanceObject = nil;
這條線是罪魁禍首:
self.arrayOfPerformances = [[NSMutableArray alloc]init];
alloc / init之后的保留計數為1。 通過arrayOfPerformances
屬性setter設置值會再次增加保留計數(因為它是一個retain屬性)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.