views:

48

answers:

2

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?

+2  A: 

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]];
Jeroen de Leeuw
I am aware of that ... but I was clutching at straws ;) I've discovered the source of my issues though. Turns out you need to create an NSAutoreleasePool when you create a seperate thread :(
Goz
A: 

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

Goz