2009-09-03 99 views
1

我使用NSKeyedUnarchiver unarchiveObjectWithFile:来读取应用程序数据。当与仪器泄漏运行,据我所知,以下产生泄漏:IPhone - NSKeyedUnarchiver内存泄漏

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

是生产泄漏任何想法?

回答

2

我的猜测是,你的内存泄漏是由这一行造成的:

[applicationConfig retain]; 

或该行:

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

内存被unarchiveObjectWithFile:分配,但泄漏会由对象上的额外保留引起的。确保你正在释放applicationConfig

+0

我想我读了,我必须保留自我没有分配它返回的对象。你能对此有所了解吗? – Brian

+1

是的,你必须保留它。因为你保留了它,所以你也必须在某个地方释放它。内存泄漏将是由于缺少版本引起的。 –

+0

我在应用程序委托的dealloc方法(所有这些代码所在的位置)中释放applicationConfig。所以我仍然不明白报道的泄漏。它可能会认为会有泄漏,因为它没有在同一个方法中看到匹配的版本?谢谢你的帮助。 – Brian