objective-c – ARC存储器泄漏

前端之家收集整理的这篇文章主要介绍了objective-c – 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的情况下编译上面的代码. Analyze工具报告可能的内存泄漏,因为imageWithCGImage ::返回计数为1的UIImage,然后引用丢失.泄漏仪器报告根本没有内存泄漏.这里发生了什么?

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

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

解决方法

ARC不管理C类型,可以考虑CGImage.完成CGImageRelease(图像)后,必须手动释放引用;
+(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,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);
            }
         }
    }
}
原文链接:https://www.f2er.com/c/119525.html

猜你在找的C&C++相关文章