iPhone - NSKeyedUnarchiver 内存泄漏
我正在使用 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];
会产生泄漏吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测是,您的内存泄漏是由这一行引起的:
或这一行:
The memory is being allocated in
unarchiveObjectWithFile:
,但泄漏将由额外的保留引起在物体上。确保您正确释放applicationConfig
。My guess is that your memory leak is caused by this line:
or this line:
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 releasingapplicationConfig
appropriately.