This question is in regards to UIView’s -drawRect function.
The Set-Up:
My app consists of multi-page PDF document that can be flipped through via a paging-enabled ScrollView. Each page (PDFDisplayView) is a UIView customized to use Core Graphics CGPDF functionality to draw a specific page of the PDF document. The Scroll View tries to optimize memory by loading the pages that are in view and unloading unused pages. Loading a page initializes a UIViewController that adds its view (PDFDisplayView) to the ScrollView, which calls the -drawRect function of the PDFDisplayView (shown below).
The Mystery:
Adding the view (PDFDisplayView) to its superview (the ScrollView) calls the -drawRect function, and in Instruments Object Allocations visualizer, the memory size grows. The mystery is that, although -drawRect seems to increase memory usage, removing the view from the superview (ScrollView) on unload does not seem to reduce the memory usage, as the visualizer graph keeps going up, not down. The result is that memory usage continues to expand as you use the app, which causes memory warnings and eventual crashing…
Other Info:
I’ve checked all other aspects of my code to make sure I am not leaking memory elsewhere — all seems fine. This led me to suspect drawRect as being the culprit. I’ve included the code below. Please tell me what you think. Thanks.
- (void)drawRect:(CGRect)rect {
CGPDFPageRef thePageRef = [[PDFReaderAppDelegate sharedAppDelegate] getPageRefForPage:self.currentPage];
if(thePageRef)
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextTranslateCTM(ctx, 0.0, [self bounds].size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
CGContextConcatCTM(ctx,
CGPDFPageGetDrawingTransform(thePageRef, kCGPDFCropBox,
[self bounds], 0, true));
CGContextDrawPDFPage(ctx, thePageRef);
CGContextRestoreGState(ctx);
NSLog(@"Drew PDFDisplayView of page %i (-drawRect)", self.currentPage);
}
}
The memory malloc’d in your drawRect will persist until you release the document. Periodically releasing and reopening the document is the only way around this that I’ve found.