2012-05-21 73 views
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]; 
} 

回答

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; 
+0

非常感謝你的幫助,凱文! :) – trillions

+0

真正有用的答案! –

1

您可以釋放CGImageRef你做。 CGBitmapContextCreateImage在名稱中有「創建」,這意味着(Apple嚴格遵守其命名約定),您負責釋放此內存。

替換最後一行與

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

非常感謝Kreiri! – trillions