1

NSKeyedUnarchiver unarchiveObjectWithFile:用来读取应用程序数据。在 Instruments 中使用 Leaks 运行时,我被告知以下会产生泄漏:

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

是否产生泄漏?

4

1 回答 1

2

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

[applicationConfig retain];

或这一行:

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

内存正在分配unarchiveObjectWithFile:但泄漏将由对象上的额外保留引起。确保您正在applicationConfig适当地释放。

于 2009-09-03T13:21:56.570 回答