【发布时间】:2015-02-12 06:51:22
【问题描述】:
我有一个 UIViewController,里面有一个自定义的 UIView。这个自定义 UIView 使用 drawRect 和 CoreGraphics 绘制一个 pdf。 UIViewController (pdfViewController) 被多次加载:
[self.revealViewController setFrontViewController:[[pdfViewController alloc] initWithPDF:pdfs[indexPath.row] uiColor:[self colorWithRGB:colors[indexPath.row][0]]]];
自定义 UIView 如下所示:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSURL *url = [NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:PDF]];
// Get GraphicsContext
CGContextRef ctx = UIGraphicsGetCurrentContext();
// Open PDF Document
CGPDFDocumentRef pdfDocument = CGPDFDocumentCreateWithURL((CFURLRef)url);
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDocument, Page);
// Get PDF Dimensions
CGRect cropRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFCropBox);
// Set white background
CGContextSetRGBFillColor(ctx, 255.0, 255.0, 255.0, 1.0);
CGContextFillRect(ctx, rect);
// Flip Coordinates and reset Origin
CGContextGetCTM(ctx);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -rect.size.height);
// Set render quality
CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);
// Scale Matrix
CGContextScaleCTM(ctx, rect.size.height/cropRect.size.height,rect.size.height/cropRect.size.height);
CGContextTranslateCTM(ctx, -cropRect.origin.x, -cropRect.origin.y);
// Draw PDF
CGContextDrawPDFPage(ctx, pdfPage);
CGPDFPageRelease(pdfPage);
CGPDFDocumentRelease(pdfDocument);
}
内存不会被释放,每次加载 UIView 时,UIViewController 内存都会增加 ca。 6MB:/
这是内存使用情况的图片:
任何帮助将不胜感激,请随时询问更多信息
更新:
drawRect 中的 UIViews 手动内存管理非常好。由于(强)委托引用,UIView 本身没有释放自己。再次感谢所有答案
【问题讨论】:
-
嗯,嗯?您注释掉了释放资源:
//CGContextRelease(ctx);。这背后的想法是什么? -
取消注释此行会引发警告并且应用程序崩溃:CGContextResetState: invalid context 0x10953d010。这是一个严重的错误。此应用程序或它使用的库正在使用无效的上下文,从而导致系统稳定性和可靠性的整体下降。此通知是出于礼貌:请解决此问题。这将成为即将到来的更新中的致命错误。
-
调用 CGContextRelease() 的问题是你没有创建它。它只是系统打算让您绘制的已经存在的上下文。
-
那么如何才能完全卸载内存以避免内存泄漏呢?
-
这是在 ARC 下还是手动内存管理?
标签: ios objective-c pdf memory-leaks core-graphics