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

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

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

您正在泄漏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; 

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

用最后一行替换

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