0

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Lars
  • 1
  • 2
  • 1
  • I think there is a problem with PDFKit which allocate lot of CoreGraphics objects during PDFPage generation. Memory is not seen as leaked by Instruments’ but seems to not deallocate if not in main queue for some time. I have the same problem but no solution, sorry. – Ptit Xav Aug 19 '23 at 16:59

0 Answers0