1

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

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

2 回答 2

9

您正在泄漏CGImage对象(存储在您的image变量中)。您可以通过在创建UIImage.

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

这样做的原因是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;
于 2012-05-21T22:21:26.807 回答
1

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

将最后一行替换为

UIImage *uiimage = [UIImage imageWithCGImage:image];
CGImageRelease(image);
return uiimage;
于 2012-05-21T22:25:59.567 回答