Why is this Objective-C memory leak code?

Why is this leak?

arrayOfPerformances- this property NSMutableArray, (nonatomic, retain)which is synthesized.

currentPerformanceObject- this property Performance *, (nonatomic, retain)which is synthesized.

Performance is a custom class

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

    [self.arrayOfPerformances addObject:currentPerformanceObject];
    [currentPerformanceObject release];
    currentPerformanceObject = nil;
+3
source share
3 answers

You create a new array and save it at the same time on this line, because you call the property installer (retain)with dot notation:

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

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

Because of this, a locally created array leaks because you are not releasing it. You must autodetect this array or create a temporary local var, assign and then free the local var, for example:

// 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];
+11
source

.arrayOfPerformances ( -dealloc), , , .

-dealloc:

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

, @BoltClock, NSMutableArray. - autoreleased:

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;
+4

:

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

1 alloc/init. arrayOfPerformances ( ).

+1

Source: https://habr.com/ru/post/1777584/


All Articles