ARC存储器泄漏

Z.O*_*.O. 7 memory memory-leaks objective-c ios automatic-ref-counting

+(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)] ];
            }
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

在启用ARC的情况下编译上面的代码.Analyze工具报告可能的内存泄漏,因为imageWithCGImage ::返回带有count +1的UIImage,然后引用丢失.泄漏仪器报告根本没有内存泄漏.这里发生了什么?

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

感谢任何能提供任何建议的人.

Cod*_*aFi 8

ARC不管理C类型,可以考虑CGImage.完成后必须手动释放引用CGImageRelease(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);
            }
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 另请参阅我的问题的接受答案:http://stackoverflow.com/questions/6260256/what-kind-of-leaks-does-automatic-reference-counting-in-objective-c-not-prevent/6388601# 6388601 (2认同)