【问题标题】:Memory demand increases when running for loop运行 for 循环时内存需求增加
【发布时间】:2015-12-17 08:27:23
【问题描述】:

我尝试使用以下代码从 pdf 页面生成 jpeg 文件。 这个应用程序的内存需求随着每次迭代而增加,但 Instruments 没有显示任何泄漏。 似乎只有在 for 循环完成时才会释放内存,因此对于 1000 页的 pdf,应用程序会消耗所有内存并且系统开始使用虚拟内存。 有什么提示吗?

let pdf = PDFDocument(URL: sourceURL)
var thumbImageURL:NSURL
var pdfImage:NSImage
let thumbRect = NSMakeRect(0.0, 0.0, ceil(CGFloat(Float(pdf.pageAtIndex(0).boundsForBox(kPDFDisplayBoxMediaBox).width) * self.thumbHeight / Float(pdf.pageAtIndex(0).boundsForBox(kPDFDisplayBoxMediaBox).height))), CGFloat(self.thumbHeight))
let rep = NSBitmapImageRep.init(bitmapDataPlanes: nil, pixelsWide: Int(thumbRect.width), pixelsHigh: Int(thumbRect.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)!               
NSGraphicsContext.saveGraphicsState()
let myContext = NSGraphicsContext.init(bitmapImageRep: rep)
NSGraphicsContext.setCurrentContext(myContext)
var jpegImage:NSData
       for i in 0 ..< pdf.pageCount(){

            thumbImageURL = self.targetURL!.URLByAppendingPathComponent("/pages/\(i+1)-thumb.jpg")
            pdfImage = NSImage.init(data: pdf.pageAtIndex(i).dataRepresentation())!
            pdfImage.drawInRect(thumbRect, fromRect: NSZeroRect, operation: NSCompositingOperation.CompositeCopy, fraction: 1.0)
            jpegImage = rep.representationUsingType(NSBitmapImageFileType.NSJPEGFileType, properties: [:])!
            jpegImage.writeToURL(thumbImageURL, atomically: false)
        }
            NSGraphicsContext.restoreGraphicsState()

【问题讨论】:

    标签: macos swift for-loop memory


    【解决方案1】:

    尝试为循环创建一个自动释放池块,这种机制可以减少峰值内存占用:

    https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html#//apple_ref/doc/uid/20000047-CJBFBEDI

    为此,您必须像这样将代码包装在循环中:

    for i in 0 ..< pdf.pageCount(){    
        autoreleasepool {
            // ...
        }
    }
    

    【讨论】:

    • 非常感谢,就是这样! (我不知道 Swift 也有和 Objective-C 一样的 autoreleasepool 语句)
    猜你喜欢
    • 2014-12-12
    • 2019-01-17
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 2017-06-20
    • 1970-01-01
    相关资源
    最近更新 更多