how to release memory created by CGContextDrawPDFPage
<p>This is ipad magazine application. We need to read PDF and convert to PNG image for thumnail. After reading PDF before conversion, which is calling CGContextDrawPDFPage, the memory goes up quickly and never free up till crash. I tried in many ways but it does not work. I really appreciate if anyone could help.</p>

<p>CGContextDrawPDFPage(context, aPage); //this is the memory killer</p>

<p>The following is the complete code:</p>

<p>-(UIImage *)image :(CGPDFPageRef)aPage rect:(CGRect)aRect
{
    CGRect pdfcropBox = CGRectIntegral(CGPDFPageGetBoxRect(aPage, kCGPDFCropBox));</p>

<pre><code>if ((float)pdfcropBox.size.width/(float)pdfcropBox.size.height &gt; 
    (float)aRect.size.width/(float)aRect.size.height) //pdf width too big
{
    aRect.size.height = aRect.size.width * pdfcropBox.size.height / pdfcropBox.size.width;
}
//CGRect pdfcropBox = aRect;    

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,aRect.size.width,
                                             aRect.size.height,
                                             8,
                                             (int)aRect.size.width * 4,
                                             colorSpace, 
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

CGColorSpaceRelease(colorSpace);
colorSpace = nil;

CGPDFPageRetain(aPage);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(aPage,
                                                              kCGPDFCropBox,
                                                              CGRectMake(0, 0, aRect.size.width,aRect.size.height),
                                                              0, true);
CGContextSaveGState(context);
CGContextConcatCTM(context, pdfTransform);
CGContextDrawPDFPage(context, aPage);
CGPDFPageRelease (aPage);
aPage = nil;
CGContextRestoreGState(context);    
CGImageRef image = CGBitmapContextCreateImage(context);
UIImage *resultingImage =  [UIImage imageWithCGImage:image];
CGContextClearRect(context, aRect);
CGContextClearRect(context, pdfcropBox);

CGContextRelease(context);
CGImageRelease(image);
context = nil; 

NSLog(@"colorSpace :%d,aPage :%d,context :%d",[colorSpace retainCount],[aPage retainCount],[context retainCount]);
return resultingImage;
</code></pre>

<p>}</p>
