I’m trying to import PDF documents to my app with the share extension. To avoid memory leaks, my plan is to import every page separately. I’ve removed many parts of my code to isolate the bug. But even without any CoreData context I’m still struggling with memory leaks:
private func importPDFToCoreData(completion: @escaping (_ success: Bool) -> Void) {
guard let extensionItem = extensionContext?.inputItems.first as? NSExtensionItem,
let attachment = extensionItem.attachments?.first else {
completion(false)
return
}
attachment.loadItem(forTypeIdentifier: UTType.pdf.identifier as String, options: nil, completionHandler: { (result, error) in
guard let url = result as? URL else {
completion(false)
return
}
guard let pdfDocument = PDFDocument(url: url) else {
completion(false)
return
}
for pageIndex in 0..<pdfDocument.pageCount {
autoreleasepool {
let pdfPage = pdfDocument.page(at: pageIndex)!
let document = PDFDocument()
document.insert(pdfPage, at: 0)
let data = document.dataRepresentation()
// Store the data in Core Data
}
}
completion(true)
})
}
What am I doing wrong?
I thought the memory storage should be cleared automatically after every single execution of the loop.
I also tried to clear the memory manually by using data
as an optional value and setting its value to nil after storing it in CoreData. But it isn’t working as well.