CIContext createCGImage内存泄漏?

CIContext createCGImage memory leak?

我遇到了内存泄漏。根据 Profiler(带分配),它发生在 CIContext 的 createCGImage 函数中。我一直在 Whosebug 上寻找并发现类似的问题,但我还没有找到解决方案。我试图将它包装在一个自动释放池中,但我仍然有内存泄漏。

如何从 CIContext 创建 CGImage 而不会在 swift4 中泄漏内存?

func session(_ session: ARSession, didUpdate frame: ARFrame) {
    // Only run when currentFrame is finished
    guard self.currentPixelBuffer == nil else { return } // , case .normal = frame.camera.trackingState
    self.currentPixelBuffer = frame.capturedImage

    guard let currentPixelBuffer = self.currentPixelBuffer else {return }

    let ciImage = CIImage(cvPixelBuffer: currentPixelBuffer).oriented(CGImagePropertyOrientation.init(UIDevice.current.orientation))

    let cgImage: CGImage? = self.context?.createCGImage(ciImage, from: ciImage.extent)
    // var cgImage: CGImage?
    // autoreleasepool { [weak self] () -> () in
    //     cgImage = self?.context?.createCGImage(ciImage, from: ciImage.extent)
    // }

    guard let unwrappedCgImage = cgImage else { return }
    let uiImage = UIImage.init(cgImage: unwrappedCgImage)

    let visionImage = VisionImage(image: uiImage)

    self.backgroundQueue.async {
        self.textDetector?.detect(in: visionImage, completion: { [weak self] (features, error) in
        ...

P.s. here is my context declaration:

var context: CIContext? = CIContext.init(options: nil)

因此,问题实际上出在 "self.textDetector?.detect(in: visionImage ..." 调用中。 它保留了对 visionImage 的强烈引用。

我无法解决这个问题,但我可以通过让 VisionImage 考虑旋转而不是自己旋转图像来解决这个问题....

我最终得到了这个工作代码:

func session(_ session: ARSession, didUpdate frame: ARFrame) {
    // Only run when currentFrame is finished
    guard self.currentPixelBuffer == nil else { return } // , case .normal = frame.camera.trackingState
    self.currentPixelBuffer = frame.capturedImage

    guard let currentPixelBuffer = self.currentPixelBuffer else { return }
    let visionImage = VisionImage(buffer: self.getCMSampleBuffer(pixelBuffer: currentPixelBuffer))

    let metadata = VisionImageMetadata()
    switch UIApplication.shared.statusBarOrientation {
    case .landscapeLeft:
        metadata.orientation = .bottomRight
    case .landscapeRight:
        metadata.orientation = .topLeft
    case .portrait:
        metadata.orientation = .rightTop
    case .portraitUpsideDown:
        metadata.orientation = .leftBottom
    default:
        metadata.orientation = .topLeft
    }

    visionImage.metadata = metadata

    self.backgroundQueue.async {
        self.textDetector?.detect(in: visionImage, completion: { [weak self] (features, error) in