How to deal with out of memory problem while create thumbnail by PDFKit

Summary

PDFKit has a method thumbnailOfSize: for create thumbnail but when you create thumbnail of all page by this method, memory consumption is increasing and it's cause of app crash.

Solution

You have to release PDFDocument instance that owner of PDFPage for release consumed memory by thumbnail creation. So you can release consumed memory soon by create PDFDocument for thumbnail creation only and release it.

Sample code

NSString* pdfFilePath = @"file path of PDF file";
PDFDocument* pdfDocument = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:pdfFilePath]];  // A) 
NSUInteger pageCount = pdfDocument.pageCount;

for(int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
    @autoreleasepool {  // C)
        PDFDocument* _pdfDocument = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:pdfFilePath]];  // B)
        PDFPage *pdfPage = [_pdfDocument pageAtIndex:pageIndex];
        UIImage *thumbnailImg = [pdfPage thumbnailOfSize:CGSizeMake(50, 50) forBox:kPDFDisplayBoxCropBox];
        //  do something
    }
}

A) This is main PDFDocument instance that used for show PDF and so on. *Usually, it's held by property of some class.

B) This is PDFDocument for thumbnail creation only. It's release by @autoreleasepool soon.

C) This is required for release PDFDocument instance under the ARC(Automatic Reference Counting) environment.