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

Mau*_*imo 3 iphone memory-leaks objective-c

为什么泄漏?

arrayOfPerformancesNSMutableArray,(nonatomic, retain)该合成属性.

currentPerformanceObjectPerformance *,(nonatomic, retain)该合成属性.

Performance 是一个自定义类

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

    [self.arrayOfPerformances addObject:currentPerformanceObject];
    [currentPerformanceObject release];
    currentPerformanceObject = nil;
Run Code Online (Sandbox Code Playgroud)

Bol*_*ock 11

您正在创建一个新数组在此行中同时保留它,因为您正在(retain)使用点表示法调用属性设置器:

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

// The offending code
self.arrayOfPerformances = [[NSMutableArray alloc]init];
Run Code Online (Sandbox Code Playgroud)

因此,本地创建的数组正在泄漏,因为您没有释放它.您应该自动释放该数组,或者创建一个临时的本地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];
Run Code Online (Sandbox Code Playgroud)