下面的代码是否有潜在的内存泄漏?

时间:2012-05-21 22:16:36

标签: ios

它返回的最后两行代码给了我一个潜在的内存泄漏警告。 .....这是一个真正的积极警告还是误报警告?如果是真的,我该如何解决?非常感谢你的帮助!

-(UIImage*)setMenuImage:(UIImage*)inImage isColor:(Boolean)bColor
{ 
    int w = inImage.size.width + (_borderDeep * 2);
    int h = inImage.size.height + (_borderDeep * 2);

    CGColorSpaceRef colorSpace;
    CGContextRef context;

    if (YES == bColor)
    {
        colorSpace = CGColorSpaceCreateDeviceRGB();
        context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
    }
    else
    {
        colorSpace = CGColorSpaceCreateDeviceGray();
        context = CGBitmapContextCreate(NULL, w, h, 8, w, colorSpace, kCGImageAlphaNone);        
    }

    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);

    CGContextDrawImage(context, CGRectMake(_borderDeep, _borderDeep, inImage.size.width, inImage.size.height), inImage.CGImage);

    CGImageRef image = CGBitmapContextCreateImage(context);
    CGContextRelease(context); //releasing context
    CGColorSpaceRelease(colorSpace); //releasing colorSpace

    //// The two lines of code above caused Analyzer gives me a warning of potential leak.....Is this a true positive warning or false positive warning? If true, how do i fix it?
    return [UIImage imageWithCGImage:image];
}

2 个答案:

答案 0 :(得分:9)

您正在泄漏CGImage对象(存储在image变量中)。您可以在创建UIImage后发布图片来解决此问题。

UIImage *uiImage = [UIImage imageWithCGImage:image];
CGImageRelease(image);
return uiImage;

原因是CoreGraphics遵循CoreFoundation所有权规则;在这种情况下,"Create" rule。即,具有“创建”(或“复制”)的函数返回您需要自己释放的对象。因此,在这种情况下,CGBitmapContextCreateImage()将返回您负责释放的CGImageRef


顺便说一下,为什么不使用UIGraphics便利功能来创建上下文?这些将处理在结果UIImage上放置正确的比例。如果您想匹配输入图像,也可以这样做

CGSize size = inImage.size;
size.width += _borderDeep*2;
size.height += _borderDeep*2;
UIGraphicsBeginImageContextWithOptions(size, NO, inImage.scale); // could pass YES for opaque if you know it will be
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
[inImage drawInRect:(CGRect){{_borderDeep, _borderDeep}, inImage.size}];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;

答案 1 :(得分:1)

你必须释放你制作的CGImageRef。 CGBitmapContextCreateImage在名称中有“创建”,这意味着(Apple严格遵守其命名约定),您负责释放此内存。

替换最后一行
UIImage *uiimage = [UIImage imageWithCGImage:image];
CGImageRelease(image);
return uiimage;