NSDictionary initWithContentsOfFile内存泄漏问题

时间:2013-06-13 08:33:11

标签: ios memory-leaks

我正在使用静态分析器检查我的代码的内存泄漏,我发现以下部分有潜在的泄漏。

NSString *path = nil;
NSString *tutorialPath = nil;
if (CC_CONTENT_SCALE_FACTOR() == 2)
{
    path = [[NSBundle mainBundle] pathForResource:@"sheetObjects-hd" ofType:@"plist"];
    tutorialPath = [[NSBundle mainBundle] pathForResource:@"sheetTutorial-hd" ofType:@"plist"];
} else
{
    path = [[NSBundle mainBundle] pathForResource:@"sheetObjects" ofType:@"plist"];
    tutorialPath = [[NSBundle mainBundle] pathForResource:@"sheetTutorial" ofType:@"plist"];
}

_animDataDictionary = [[[NSDictionary alloc] initWithContentsOfFile:path] objectForKey:@"frames"];
_tutorialAnimDataDictionary = [[[NSDictionary alloc] initWithContentsOfFile:tutorialPath] objectForKey:@"frames"];

问题在于这两行:

_animDataDictionary = [[[NSDictionary alloc] initWithContentsOfFile:path] objectForKey:@"frames"];
_tutorialAnimDataDictionary = [[[NSDictionary alloc] initWithContentsOfFile:tutorialPath] objectForKey:@"frames"];

我已经检查了我的dealloc代码,我很确定它们已被正确释放。

这就是我定义实例的方式:

NSDictionary *_animDataDictionary;
NSDictionary *_tutorialAnimDataDictionary;

dealloc功能:

[_animDataDictionary release];
_animDataDictionary = nil;
[_tutorialAnimDataDictionary release];
_tutorialAnimDataDictionary = nil;
[super dealloc];

通过查看其他相关问题,我看到人们抱怨类似的错误,但没有人真正得到答案,并知道它为什么会发生。

我有大量与此代码相关的泄漏,我认为必须将其删除。

谢谢!

2 个答案:

答案 0 :(得分:2)

正如静态分析器指出的那样,我认为你正在泄漏你的NSDictionary对象。您没有将[[NSDictionary alloc] initWithContentsOfFile:path][[NSDictionary alloc] initWithContentsOfFile:tutorialPath]的结果存储在任何位置,因此您无法向这些对象发送显式发布消息。

尝试在创建中间词典后添加自动释放调用,例如:

_animDataDictionary = [[[[NSDictionary alloc] initWithContentsOfFile:path] autorelease] objectForKey:@"frames"];
_tutorialAnimDataDictionary = [[[[NSDictionary alloc] initWithContentsOfFile:tutorialPath] autorelease] objectForKey:@"frames"];

答案 1 :(得分:0)

首先:您确定调用了dealloc方法吗? 在其中添加NSLog以确保您的类已取消分配。 如果没有,问题不在该类的代码中,而是在使用(分配/创建)它的类的代码中。

第二,你分配字典的方法只调用一次?或者你可以多次拨打这些电话:

_animDataDictionary = [[[NSDictionary alloc] initWithContentsOfFile:path] objectForKey:@"frames"];
_tutorialAnimDataDictionary = [[[NSDictionary alloc] initWithContentsOfFile:tutorialPath] objectForKey:@"frames"];

在最后一种情况下,您需要在创建新词典之前释放2个词典:

[_animDataDictionary release]; // the first time it's = nil, and calling this line has no problem anyway
_animDataDictionary = [[[NSDictionary alloc] initWithContentsOfFile:path] objectForKey:@"frames"];
[_tutorialAnimDataDictionary release];
_tutorialAnimDataDictionary = [[[NSDictionary alloc] initWithContentsOfFile:tutorialPath] objectForKey:@"frames"];