XCode 分析器:对象的潜在泄漏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14524273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XCode Analyzer : Potential leak of an object
提问by Max
here is a piece of code, could you help me managing memory correctly in it please ?
这是一段代码,你能帮我正确管理内存吗?
- (void) buildSpritesWithName:(NSString*)sN {
self.arrayPages = [[NSMutableArray alloc] initWithCapacity:self.numPages];
NSString *spriteName0 = [NSString stringWithFormat:@"%@%i.png", sN, 0];
CCSprite *temp0 = [CCSprite spriteWithSpriteFrameName:spriteName0];
NSLog(@"temp sprite %@ size : %f / %f",spriteName0, temp0.contentSize.width, temp0.contentSize.height);
self.imgSize = CGSizeMake(temp0.contentSize.width, temp0.contentSize.height);
for (int c = 1; c <= numberOfWheelFacesCycles; c++) {
for (int x = 1; x <= self.numPages; x++) {
NSString *spriteName = [NSString stringWithFormat:@"%@%i.png",sN, x];
CCSprite *temp = [CCSprite spriteWithSpriteFrameName:spriteName];
[self.arrayPages addObject:temp];
}
}
NSLog(@"%i Pages built",self.arrayPages.count);
}
Analyzer says "Potential leak of an object" at line :
分析器在第 1 行显示“对象的潜在泄漏”:
NSString *spriteName0 = [NSString stringWithFormat:@"%@%i.png", sN, 0];
Why that ? NSString is autorelease right ? so which object could be leaked ?
为什么 ?NSString 是自动释放的吧?那么哪个对象可能会泄漏?
I have the following in another class, again, what's the problem :
我在另一堂课上有以下内容,又是什么问题:
self.name = [playersNames objectAtIndex:type];
By the way, if the management of the loop is not good, could you advice as well ?
顺便说一句,如果循环的管理不好,您也可以提出建议吗?
Thanks for your help
谢谢你的帮助
回答by Extra Savtheitroad-Faire
Look at your property or accessor for arrayPages
. If it retains, then your potential leak arises when you call:
查看您的属性或访问器以获取arrayPages
. 如果它保留,那么当您调用时可能会出现泄漏:
self.arrayPages = [[NSMutableArray alloc] initWithCapacity:self.numPages];
If arrayPages
retains, then do this instead:
如果arrayPages
保留,则改为执行此操作:
self.arrayPages = [[[NSMutableArray alloc] initWithCapacity:self.numPages] autorelease];
or more simply:
或更简单地说:
self.arrayPages = [NSMutableArray arrayWithCapacity:self.numPages];
As for your loop, it looks all right, but beware of creating a lot of autoreleased objects inside it; they aren't released until some point later.
至于你的循环,它看起来不错,但要注意在它里面创建了很多自动释放的对象;它们直到某个时间点之后才会被释放。