Objective C memory leak problem
I have the memory leak problem in the following objective c code. The boldasterisked(***
) line is the line with memory leak (mentioned in instrument). Any idea of it? Thanks.
- (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(imgInRe开发者_JS百科ct);
***imgResult = [UIImage imageWithCGImage:CGBitmapContextCreateImage(pictureContext)];***
CGContextRelease(pictureContext);
free(pictureData);
return imgResult;
}
imgResult = [UIImage imageWithCGImage:CGBitmapContextCreateImage(pictureContext)];
You create a CGImage
, pass it to a UIImage
factory method, and then forget about it. You're leaking the CGImage
.
Do this instead:
CGImageRef cgResult = CGBitmapContextCreateImage(pictureContext);
if (cgResult) {
imgResult = [UIImage imageWithCGImage: cgResult];
CGImageRelease(cgResult);
}
精彩评论