R – IPhone – NSKeyedUnarchiver memory leak

cocoacocoa-touchiphonenskeyedarchiver

I am using NSKeyedUnarchiver unarchiveObjectWithFile: to read in application data. When running with Leaks in Instruments, I am told that the following produces a leak:

{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *archivePath = [[NSString alloc]initWithFormat:@"%@/Config.archive", documentsDirectory];

    //Following line produces memory leak
    applicationConfig = [NSKeyedUnarchiver unarchiveObjectWithFile:archivePath];

    [archivePath release];

    if( applicationConfig == nil )
    {
        applicationConfig = [[Config alloc]init];
    }
    else
    {
        [applicationConfig retain];
    }
}

The line:

applicationConfig = [NSKeyedUnarchiver unarchiveObjectWithFile:archivePath];

is producing a memory leak of 32 Bytes. applicationConfig is an instance variable. My initWithCode function simply does:

- (id)initWithCoder:(NSCoder *)coder {
    if( self = [super init] )
    {
                //NSMutableArray
        accounts = [[coder decodeObjectForKey:@"Accounts"] retain];
        //Int
                activeAccount = [coder decodeIntForKey:@"ActiveAccount"];       
    }
    return self;
}

Any idea of why

applicationConfig = [NSKeyedUnarchiver unarchiveObjectWithFile:archivePath];

is producing a leak?

Best Answer

My guess is that your memory leak is caused by this line:

[applicationConfig retain];

or this line:

accounts = [[coder decodeObjectForKey:@"Accounts"] retain];

The memory is being allocated in unarchiveObjectWithFile:, but the leak will be caused by an extra retain on the object. Make sure that you are releasing applicationConfig appropriately.

Related Topic