I am also struggling with this problem, and while Bill's answer gave me the key, I had to do it differently. In my situation, there is a variable number of source PDF files that are copied to the destination PDF, so I just can't just move the UIGraphicsEndContext to CGPDFDocumentRelease . The code structure looks something like this:
UIGraphicsBeginPDFContextToFile(...); // ... for each attachment pdf { srcPdf = CGPDFDocumentCreateWithURL(...); // open source PDF // ... UIGraphicsBeginPDFPageWithInfo(...); // new page in target PDF, this randomly crashes // ... CGPDFDocumentRelease(srcPdf); // close source PDF } // ... UIGraphicsEndPDFContext();
So instead, I tried to grab the links to all the source PDF files that he used and free them all after completing the remaining destination PDF file, much later in the code. This is kind of ugly, because it gives responsibility away and holds all the memory to the end, and is not freed after each of them is displayed ... BUT it really works! It is hard to say definitively, since it was an accidental failure, but since then I have not seen it, and I have scored it a lot, trying to repeat it.
pdfRefs = [[NSPointerArray alloc] init]; UIGraphicsBeginPDFContextToFile(...); // ... for each attachment pdf { srcPdf = CGPDFDocumentCreateWithURL(...); // open source PDF // ... UIGraphicsBeginPDFPageWithInfo(...); // new page in target PDF, this randomly crashes // ... [pdfRefs addPointer:srcPdf]; // store for later closing } // ... UIGraphicsEndPDFContext(); for each srcPdf in pdfRefs { CGPDFDocumentRelease(srcPdf); // close it here }
source share