Objective C内存泄漏问题

时间:2010-12-01 04:51:10

标签: objective-c memory-leaks

我在以下目标c代码中遇到内存泄漏问题。 粗体带星号(***)行是内存泄漏的行(在仪器中提到)。有什么想法吗?感谢。

- (UIImage*)part:(float)part ofImage:(UIImage*)imgObject withMask:(UIImage*)imgMask {
 UIImage *imgResult = nil;
 CGRect rcMask = CGRectMake(0.0f, 0.0f, imgMask.size.width, imgMask.size.height);
 CGRect rcObject = CGRectMake(0.5f * (rcMask.size.width - imgObject.size.width), 0.0f, imgObject.size.width, imgObject.size.height * part);

 BytePtr pictureData = (BytePtr)malloc(rcMask.size.width * rcMask.size.height * 4);
 CGContextRef pictureContext = CGBitmapContextCreate(pictureData, rcMask.size.width,              rcMask.size.height,8, rcMask.size.width * 4,CGImageGetColorSpace(imgObject.CGImage),              kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

 CGContextClipToMask(pictureContext, rcMask, imgMask.CGImage);
 CGImageRef imgInRect;
 imgInRect = CGImageCreateWithImageInRect(imgObject.CGImage, rcObject);
 CGContextDrawImage(pictureContext, rcObject, imgInRect);
 CGImageRelease(imgInRect);
 ***imgResult = [UIImage imageWithCGImage:CGBitmapContextCreateImage(pictureContext)];***

 CGContextRelease(pictureContext);
 free(pictureData);
 return imgResult;
}

1 个答案:

答案 0 :(得分:5)

imgResult = [UIImage imageWithCGImage:CGBitmapContextCreateImage(pictureContext)];

您创建了CGImage,将其传递给UIImage工厂方法,然后忘掉它。你正在泄漏CGImage

请改为:

CGImageRef cgResult = CGBitmapContextCreateImage(pictureContext);
if (cgResult) {
    imgResult = [UIImage imageWithCGImage: cgResult];
    CGImageRelease(cgResult);
}