简体   繁体   English

ARC存储器泄漏

[英]Memory Leak with ARC

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

Compiled the above code with ARC enabled. 在启用ARC的情况下编译上面的代码。 The Analyze tool reports a possible memory leak since imageWithCGImage:: returns UIImage with count +1, then reference is lost. Analyze工具报告可能的内存泄漏,因为imageWithCGImage ::返回带有count +1的UIImage,然后引用丢失。 Leaks Instrument reports no memory leaks at all. 泄漏仪器报告根本没有内存泄漏。 Whats going on here? 这里发生了什么?

Furthermore, since ARC prohibits use of manually using release ect, how does one fix the leak? 此外,由于ARC禁止使用手动release ,如何修复泄漏?

Thanks to anyone who can offer any advice. 感谢任何能提供任何建议的人。

ARC does not manage C-types, of which CGImage may be considered. ARC不管理C类型,可以考虑CGImage。 You must release the ref manually when you are finished with CGImageRelease(image); 完成CGImageRelease(image);后,必须手动释放引用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);
            }
         }
    }
}

None of the core foundation data structure is dealt with ARC. ARC没有处理任何核心基础数据结构。 Many a times this creates a problem. 很多时候这会产生问题。 In these case we have to manually release the memory. 在这些情况下,我们必须手动释放内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM