pm08
pm08

Reputation: 25

Memory leak on NSString stringByAppendingPathComponent:

Analyze is showing memory leak where I assign filePath value for fileB in the following code snippet:

NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];

NSString *filePath = [docsDir stringByAppendingPathComponent:@"/fileA"];

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
    self.propertyA = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
} else {
    //  initialize array with default values and write to data file fileA   
    [self populatePropertyAForFile:filePath];       
}

filePath = [docsDir stringByAppendingPathComponent:@"/fileB"];

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
    self.propertyB = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
} else {
    // initialize array with default values and write to data file fileB

    [self populatePropertyBForFile:filePath];

}

I understand it is because the previous value (for fileA) has not been released. But I can't figure-out how to stop this leak.

Upvotes: 1

Views: 420

Answers (1)

JeremyP
JeremyP

Reputation: 86651

No. There is nothing wrong with filePath. The problem is almost certainly with your two properties, propertyA and propertyB. If they are retain properties, then the arrays you assign to them and their contents will leak because you own the arrays you alloc and you are not releasing them. Change the lines like this:

self.propertyA = [[[NSMutableArray alloc] initWithContentsOfFile:filePath] autorelease];
                                                                        // ^^^^^^^^^^^ will release ownership of the array

Upvotes: 2

Related Questions