1

I am using static analyser to check the memory leak of my code and I found the following part has potential 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"];

The problem was with these two lines:

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

I've checked my dealloc code and I am pretty sure they are dealloced properly.

And this is how I defined the instances:

NSDictionary *_animDataDictionary;
NSDictionary *_tutorialAnimDataDictionary;

dealloc functions:

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

By checking other related questions, I have seen people complaining about the similar bugs but nobody really gets the answer and knows why it happens.

I have tons of leaks related to this code and I feel it is essential to kill it.

Thanks!

4

2 回答 2

2

正如静态分析器所指出的那样,在我看来,您正在泄漏 NSDictionary 对象。您没有在任何地方存储[[NSDictionary alloc] initWithContentsOfFile:path]or的结果,[[NSDictionary alloc] initWithContentsOfFile:tutorialPath]因此您无法向这些对象发送显式释放消息。

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

_animDataDictionary = [[[[NSDictionary alloc] initWithContentsOfFile:path] autorelease] objectForKey:@"frames"];
_tutorialAnimDataDictionary = [[[[NSDictionary alloc] initWithContentsOfFile:tutorialPath] autorelease] objectForKey:@"frames"];
于 2013-06-13T08:37:17.010 回答
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"];
于 2013-06-13T08:49:14.273 回答