ARC的内存泄漏 [英] Memory Leak with ARC

查看:91
本文介绍了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)] ];
            }
         }
    }
}

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

Compiled the above code with ARC enabled. The Analyze tool reports a possible memory leak since imageWithCGImage:: returns UIImage with count +1, then reference is lost. Leaks Instrument reports no memory leaks at all. Whats going on here?

此外,由于ARC禁止使用release ect进行手动操作,因此如何解决泄漏?

Furthermore, since ARC prohibits use of manually using release ect, how does one fix the leak?

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

Thanks to anyone who can offer any advice.

推荐答案

ARC不管理C类型,可以考虑使用CGImage.完成CGImageRelease(image);

ARC does not manage C-types, of which CGImage may be considered. You must release the ref manually when you are finished with 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);
            }
         }
    }
}

这篇关于ARC的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆