Swift UIImage .jpegData 内存泄漏问题

Swift UIImage .jpegData memory leak issue

我有一些代码可以接受 UIImage 并将该图像保存到磁盘。此代码针对多个图像进行迭代。我注意到每次代码运行时,我都会有内存泄漏,该泄漏会一直持续到视图被删除。

我将问题追踪到以下行: var data = image.jpegData(compressionQuality: 0.8 )

每次调用此行时,都会为压缩图像分配相应数量的内存(每次约 10 Mb),并且在视图关闭之前不会释放。我什至也尝试过删除对数据的任何使用(即引用计数应该为 0),但它仍然没有释放内存。

    func save_to_folder( tray_number: Int64, tray_type: String, image: UIImage, filename: String ) -> Bool {
        let dir = self.directory!
            .appendingPathComponent( "trays" )
            .appendingPathComponent( String( format: "tray_%04d", tray_number ) )
            .appendingPathComponent( tray_type )
        
        print( "  save_dir: \( dir.path )" )
        
        let full_filename = dir.appendingPathComponent( filename ).appendingPathExtension( "JPG" )
        print( "  full_filename: \( full_filename.path )" )
        
        do {
            try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil )
        }
        catch let error {
            print( "Error creating directory: \( error )" )
            return false
        }
        
        var data = image.jpegData(compressionQuality: 0.8 )
        /*
        do {
            try data!.write(to: full_filename, options: Data.WritingOptions.atomic )
            return true
        }
        catch let error {
            print( "Failed to write file: \( error )" )
        }
        
        data = nil
 */
        return false
    }
for itt in 0...self.URLs.count - 1{
                let closure = { [weak self] in
                    print(self!.URLs[itt])
                    let image = UIImage.init(contentsOfFile: self!.URLs[itt].relativePath)
                    //temp_bore = try! Borehole(sqlite_filename:self!.borehole!.filename)
                    let _ = self?.borehole?.save_to_folder(tray_number: tray_number, tray_type: tray_type, image: image! )
                    tray_number += 1
                    progress += 1
                    DispatchQueue.main.async {
                        alertView.message = "Adding \( progress ) of \( total )"
                    }
                }
                closure()
            }

有人知道这里发生了什么吗?为什么 jpegData 分配的内存永远不会释放?

感谢 El Tomato,我找到了解决方案。

如果其他人遇到此问题,请在您的 .jpegData 调用周围添加 autoreleasepool

autoreleasepool{
            let data = image.jpegData(compressionQuality: 0.8 )
    
            do {
                try data!.write(to: full_filename, options: Data.WritingOptions.atomic )
            }
            catch let error {
                print( "Failed to write file: \( error )" )
            }

        }