我正在维护公司的遗留应用程序,并且正在尝试减少非ARC项目(叹息)中的崩溃和内存泄漏量。我已经在函数中发现了一个巨大的内存泄漏,该函数将PDF文件转换为UIImage,但没有足够的图形上下文经验来正确识别所有问题。
泄漏内存的方法如下:
+ (UIImage *) convertPDFToImage:(NSURL *)pdfLocation withResolution:(int)resolution withProductKey:(NSString *) productKey {
CGPDFDocumentRef documentRef = CGPDFDocumentCreateWithURL((CFURLRef)pdfLocation);
if(!CGPDFDocumentIsUnlocked(documentRef))
{
NSString *hashedPassword = [MD5Hash CreateMD5HashForPDFPasswordUsingProductKey:productKey];
CGPDFDocumentUnlockWithPassword(documentRef, [hashedPassword UTF8String]);
}
CGPDFPageRef page = CGPDFDocumentGetPage(documentRef, 1);
CGRect cropBox = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
int pageRotation = CGPDFPageGetRotationAngle(page);
if ((pageRotation == 0) || (pageRotation == 180) ||(pageRotation == -180)) {
UIGraphicsBeginImageContextWithOptions(cropBox.size, NO, resolution / 72);
} else {
UIGraphicsBeginImageContextWithOptions(CGSizeMake(cropBox.size.height, cropBox.size.width), NO, resolution / 72);
}
CGContextRef context = UIGraphicsGetCurrentContext();
CGPoint point = CGPointMake(0, 0);
int rotate = CGPDFPageGetRotationAngle(page);
int zoom = 100;
CGContextSaveGState(context);
// Setup the coordinate system.
// Top left corner of the displayed page must be located at the point specified by the 'point' parameter.
CGContextTranslateCTM(context, point.x, point.y);
// Scale the page to desired zoom level.
CGContextScaleCTM(context, zoom / 100, zoom / 100);
// The coordinate system must be set to match the PDF coordinate system.
switch (rotate) {
case 0:
CGContextTranslateCTM(context, 0, cropBox.size.height);
CGContextScaleCTM(context, 1, -1);
break;
case 90:
CGContextScaleCTM(context, 1, -1);
CGContextRotateCTM(context, -M_PI / 2);
break;
case 180:
case -180:
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, cropBox.size.width, 0);
CGContextRotateCTM(context, M_PI);
break;
case 270:
case -90:
CGContextTranslateCTM(context, cropBox.size.height, cropBox.size.width);
CGContextRotateCTM(context, M_PI / 2);
CGContextScaleCTM(context, -1, 1);
break;
}
// The CropBox defines the page visible area, clip everything outside it.
CGRect clipRect = CGRectMake(0, 0, cropBox.size.width, cropBox.size.height);
CGContextAddRect(context, clipRect);
CGContextClip(context);
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextFillRect(context, clipRect);
CGContextTranslateCTM(context, -cropBox.origin.x, -cropBox.origin.y);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);
CGContextDrawPDFPage(context, page);
UIImage *pageImage = UIGraphicsGetImageFromCurrentImageContext();
CGContextRestoreGState(context);
UIGraphicsEndImageContext();
CGPDFPageRelease(page);
CGPDFDocumentRelease(documentRef);
return pageImage;
}
我已经解决了一个没有发布CGPDFPage的漏洞,但是配置文件显示这种方法仍然在略微泄漏。
非常感谢任何建议