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

tri*_*ons 1 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];
}
Run Code Online (Sandbox Code Playgroud)

Lil*_*ard 9

您正在泄漏CGImage对象(存储在image变量中).您可以通过在创建后释放图像来解决此问题UIImage.

UIImage *uiImage = [UIImage imageWithCGImage:image];
CGImageRelease(image);
return uiImage;
Run Code Online (Sandbox Code Playgroud)

原因是CoreGraphics遵循CoreFoundation所有权规则; 在这种情况下,"创建"规则.即,具有"创建"(或"复制")的函数返回您需要自己释放的对象.所以在这种情况下,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;
Run Code Online (Sandbox Code Playgroud)