已将此问题编辑为使用代码的更简单版本。TestPDF全是文本,大约有300页。当循环运行时,它在消耗2 2gb内存后崩溃。打印后,我不需要print语句中的值。但是,代码会将其保存在内存中。如何在循环结束前清除print语句内容的内存分配?
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!)
}
}
}
}我尝试过的解决方案包括autoreleasepool和在for each循环中创建一个新的PDFDocument对象并使用该对象。第二种选择确实释放了内存,但太慢了。
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!)
}
}
}
}发布于 2019-03-26 17:14:10
到目前为止,我的解决方案是在didReceiveMemoryWarning中重新加载PDFDocument
所以我有一个全局变量
var document = PDFDocument()使用它
let pdfURL = ...
document = PDFDocument(url: pdfURL)! 如果内存不足
override func didReceiveMemoryWarning() {
let pdfURL = ...
document = PDFDocument(url: pdfURL)!
}https://stackoverflow.com/questions/48957766
复制相似问题