我正在使用NSKeyedUnarchiver unarchiveObjectWithFile:读入应用程序数据。当运行Instruments中的泄漏时,我被告知以下代码会导致泄漏:
{
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];
会造成泄漏吗?
发布于 2009-09-03 13:21:57
我猜你的内存泄漏是由下面这行代码引起的:
[applicationConfig retain];或者这一行:
accounts = [[coder decodeObjectForKey:@"Accounts"] retain];内存是在unarchiveObjectWithFile:中分配的,但泄漏是由对象上的额外保留引起的。确保您适当地发布了applicationConfig。
https://stackoverflow.com/questions/1373339
复制相似问题