Goz
Goz

Reputation: 62323

Problem with iPhone memory leaking

I have a piece of Objective-C code I've inherited and the leak tracking tool has identified a memory leak in the code. I am not entirely up on the memory tracking rules of Objective-C so I'm having a real problem with understanding why the memory is leaking. The code is as follows:

+ (NSString *) getRecordingsDirectory
{   

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);   
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *tmpRecordingsDirectory = [documentsDirectory stringByAppendingPathComponent: @"Recordings"];
    NSFileManager* fileManager = [[NSFileManager alloc] init];
    BOOL result;
    if ([fileManager fileExistsAtPath:tmpRecordingsDirectory isDirectory:&result] == FALSE)
    {
        NSError* error;
        [[NSFileManager defaultManager] createDirectoryAtPath: tmpRecordingsDirectory withIntermediateDirectories:TRUE attributes:nil error:&error];
        // TODO - handle error return
    }

    [fileManager release];
    [documentsDirectory release];
    [paths release];
    return tmpRecordingsDirectory;

}

The part that is being marked as leaking is the first line. As you can see I've been playing with "release"ing the various items on there to see if it makes any difference. I thought that it ought to auto release the paths variable. This doesn't appear to be the case, however.

So can anyone tell me what I'm doing wrong and how to eliminate this memory leak?

Upvotes: 0

Views: 314

Answers (2)

Goz
Goz

Reputation: 62323

I was lacking an NSAutoreleasePool in my thread and this was what was causing my leaks :( D'oh.

Upvotes: 0

Jeroen de Leeuw
Jeroen de Leeuw

Reputation: 907

You shouldn't release the paths object and the documentsDirectory object because you didn't allocated it. Read the following documentation on releasing objects.

You can release it if you use the following code;

NSArray *paths = [[NSArray alloc] initWithArray:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)];
NSString *documentsDirectory = [[NSString alloc] initWithFormat:@"%@", [paths objectAtIndex:0]];

Upvotes: 2

Related Questions