【问题标题】:XCode Analyzer : Potential leak of an objectXCode Analyzer:对象的潜在泄漏
【发布时间】:2013-01-25 14:53:05
【问题描述】:

这是一段代码,你能帮我正确管理其中的内存吗?

- (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);
}

分析器在以下行显示“对象的潜在泄漏”:

NSString *spriteName0 = [NSString stringWithFormat:@"%@%i.png", sN, 0];

为什么? NSString 是自动释放对吗?那么哪个对象可能被泄露?

我在另一个班级有以下问题,又是什么问题:

self.name = [playersNames objectAtIndex:type];

对了,如果循环的管理不好,你能不能给点建议?

感谢您的帮助

【问题讨论】:

  • 如果您得到正确答案,请单击复选标记,以便我们都知道它已被回答。

标签: objective-c xcode memory-management memory-leaks cocos2d-iphone


【解决方案1】:

查看您的财产或访问者arrayPages。如果它保留,那么当您调用时,您的潜在泄漏就会出现:

self.arrayPages = [[NSMutableArray alloc] initWithCapacity:self.numPages];

如果arrayPages 保留,则改为这样做:

self.arrayPages = [[[NSMutableArray alloc] initWithCapacity:self.numPages] autorelease];

或更简单地说:

self.arrayPages = [NSMutableArray arrayWithCapacity:self.numPages];

至于你的循环,它看起来不错,但要注意在其中创建大量自动释放的对象;直到某个时间点之后才会发布它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多