7
+(void)setup {
    UIImage* spriteSheet = [UIImage imageNamed:@"mySpriteSheet.png"];
    CGRect rect;
    animation = [NSMutableArray arrayWithCapacity:numberOfFramesInSpriteSheet];
    int frameCount = 0;

    for (int row = 0; row < numberFrameRowsInSpriteSheet; row++) {
        for (int col = 0; col < numberFrameColsInSpriteSheet; col++) {
            frameCount++;
            if (frameCount <= numberOfFramesInSpriteSheet) {
                rect = CGRectMake(col*frameHeight, row*frameWidth, frameHeight, frameWidth);
                [animation addObject:[UIImage imageWithCGImage:CGImageCreateWithImageInRect(spriteSheet.CGImage, rect)] ];
            }
         }
    }
}

在启用 ARC 的情况下编译上述代码。分析工具报告可能存在内存泄漏,因为 imageWithCGImage:: 返回 UIImage 计数 +1,然后引用丢失。Leaks Instrument 报告根本没有内存泄漏。这里发生了什么?

此外,由于 ARC 禁止使用手动使用releaseect,如何修复泄漏?

感谢任何可以提供任何建议的人。

4

2 回答 2

8

ARC 不管理 C 类型,其中 CGImage 可以考虑。完成后必须手动释放 refCGImageRelease(image);

+(void)setup {
    UIImage* spriteSheet = [UIImage imageNamed:@"mySpriteSheet.png"];
    CGRect rect;
    animation = [NSMutableArray arrayWithCapacity:numberOfFramesInSpriteSheet];
    int frameCount = 0;

    for (int row = 0; row < numberFrameRowsInSpriteSheet; row++) {
        for (int col = 0; col < numberFrameColsInSpriteSheet; col++) {
            frameCount++;
            if (frameCount <= numberOfFramesInSpriteSheet) {
                rect = CGRectMake(col*frameHeight, row*frameWidth, frameHeight, frameWidth);
                //store our image ref so we can release it later
                //The create rule says that any C-interface method with "create" in it's name 
                //returns a +1 foundation object, which we must release manually.
                CGImageRef image = CGImageCreateWithImageInRect(spriteSheet.CGImage, rect)
                //Create a UIImage from our ref.  It is now owned by UIImage, so we may discard it.
                [animation addObject:[UIImage imageWithCGImage:image]];
                //Discard the ref.  
                CGImageRelease(image);
            }
         }
    }
}
于 2012-09-22T02:00:34.343 回答
3

核心基础数据结构都没有处理 ARC。很多时候,这会产生问题。在这种情况下,我们必须手动释放内存。

于 2012-09-22T06:23:02.487 回答