首页 > 解决方案 > Swift 中未释放内存

问题描述

我在swift中有一个简单的命令行工具,它正在执行图像操作,但内存从未释放。我已经提取了代码来重现这个问题。下面的代码只是加载 50 次 tif 图像并解压缩它,我假设 Swift 应该在每个循环结束时释放我的变量,但它不会并且最终占用超过 4 GB 的内存:

    let imageUrlPath = "folder/file.tif"
    for _ in 0...50
    {
        let sourceImg = NSImage(byReferencingFile: imageUrlPath)
        let sourceBitmapRep = NSBitmapImageRep(cgImage: sourceImg!.cgImage(forProposedRect: nil, context: nil, hints: nil)!)
        let sourceImageData = sourceBitmapRep.representation(using: .tiff, properties: [:])
    }
    RunLoop.main.run()  // Total memory taken is 4.3 GB

如何强制释放内存?

标签: swiftimagememory

解决方案


推荐阅读