为什么这个Objective-C代码会泄漏内存?

时间:2010-11-30 03:23:17

标签: iphone objective-c memory-leaks

为什么会泄漏?

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;

3 个答案:

答案 0 :(得分:11)

您正在创建一个新数组同时在此行中保留它,因为您使用点表示法调用(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];

答案 1 :(得分: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 ed属性设置为nil会为您释放该属性。您的代码应该看起来像这样:

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

答案 2 :(得分:1)

这条线是罪魁祸首:

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

alloc / init之后的保留计数为1。通过arrayOfPerformances属性setter设置值会再次增加保留计数(因为它是一个retain属性)。

相关问题