IPhone - NSKeyedUnarchiver内存泄漏

时间:2009-09-03 13:13:28

标签: iphone cocoa cocoa-touch nskeyedarchiver

我正在使用NSKeyedUnarchiver unarchiveObjectWithFile:来读取应用程序数据。当使用仪器泄漏运行时,我被告知以下产生泄漏:

{
    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];
    }
}

该行:

applicationConfig = [NSKeyedUnarchiver unarchiveObjectWithFile:archivePath];

产生32字节的内存泄漏。 applicationConfig是一个实例变量。我的initWithCode函数只是这样做:

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

知道为什么

applicationConfig = [NSKeyedUnarchiver unarchiveObjectWithFile:archivePath];

正在泄漏?

1 个答案:

答案 0 :(得分:2)

我的猜测是你的内存泄漏是由这一行引起的:

[applicationConfig retain];

或这一行:

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

内存在unarchiveObjectWithFile:中被分配,但泄漏将由对象的额外保留引起。确保您正确地发布applicationConfig