我正在使用静态分析器检查我的代码的内存泄漏,我发现以下部分有潜在的泄漏。
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];通过检查其他相关问题,我看到人们抱怨类似的bug,但没有人真正得到答案,也不知道为什么会发生这种情况。
我有大量与此代码相关的漏洞,我觉得有必要杀死它。
谢谢!
发布于 2013-06-13 16:37:17
在我看来,正如静态分析器所指出的,您正在泄漏您的NSDictionary对象。您没有存储[[NSDictionary alloc] initWithContentsOfFile:path]或[[NSDictionary alloc] initWithContentsOfFile:tutorialPath] anywhere的结果,因此不能向这些对象发送显式释放消息。
尝试在创建这些中间字典后添加自动释放调用,如下所示:
_animDataDictionary = [[[[NSDictionary alloc] initWithContentsOfFile:path] autorelease] objectForKey:@"frames"];
_tutorialAnimDataDictionary = [[[[NSDictionary alloc] initWithContentsOfFile:tutorialPath] autorelease] objectForKey:@"frames"];发布于 2013-06-13 16:49:14
第一:你确定你的dealloc方法被调用了吗?在其中添加一个NSLog,以确保您的类已被释放。如果没有,问题不在该类的代码中,而是在使用(分配/创建)它的类的代码中。
其次,分配字典的方法只调用一次吗?或者,您可以多次调用这些行:
_animDataDictionary = [[[NSDictionary alloc] initWithContentsOfFile:path] objectForKey:@"frames"];
_tutorialAnimDataDictionary = [[[NSDictionary alloc] initWithContentsOfFile:tutorialPath] objectForKey:@"frames"];在最后一种情况下,您需要在创建新字典之前发布两个字典:
[_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"];https://stackoverflow.com/questions/17082626
复制相似问题