Edited this question to use a simpler version of the code. The TestPDF is all text and about 300 pages. As the loop runs it crashes after consuming 2gb of memory. I don’t need the value in the print statement after it’s printed. However the code keeps it in memory. How to clear the memory allocation of the contents of the print statement before the loop closes?
func loadPDFDocument(){
let documentURL = Bundle.main.url(forResource: "TestPDF", withExtension: "pdf")!
if let document = PDFDocument(url: documentURL) {
for page in 1...document.pageCount {
DispatchQueue.global().async {
print(document.page(at: page)!.string!)
}
}
}
}
Solutions I have tried include autoreleasepool
and creating a new PDFDocument object in for each loop and using that. That second option does free the memory but is seriously too slow.
func loadPDFDocument(){
let documentURL = Bundle.main.url(forResource: "TestPDF", withExtension: "pdf")!
if let document = PDFDocument(url: documentURL) {
for page in 1...document.pageCount {
DispatchQueue.global().async {
let innerDocument = PDFDocument(url: documentURL)!
print(innerDocument.page(at: page)!.string!)
}
}
}
}
my solution so far has been to reload the PDFDocument in didReceiveMemoryWarning
so I have a global variable
var document = PDFDocument()
use it
let pdfURL = ...
document = PDFDocument(url: pdfURL)!
then if low memory
override func didReceiveMemoryWarning() {
let pdfURL = ...
document = PDFDocument(url: pdfURL)!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With