[英]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.