首页 > 解决方案 > Memory leak, in do-catch block. iOS, Swift

问题描述

I am looking at memory leaks in my app that uses vision to detect text.

I am getting a memory leak which when using the tree points to this line:

try imageRequestHandler.perform([self.textDetectionRequest])

I am not sure why and hope someone can help with this.

Full code below.

private func performVisionRequest(image: CGImage, orientation: CGImagePropertyOrientation) {

    DispatchQueue.global(qos: .userInitiated).async {
        do {
            var imageRequestHandler = VNImageRequestHandler(cgImage: image, orientation: orientation, options: [:])
            try imageRequestHandler.perform([self.textDetectionRequest])
        } catch let error as NSError {
            print("Failed to perform vision request: \(error)")

        }
    }
}

Here is the whole class:

import UIKit
import Vision

var noText: Bool!
var imageNo: UIImage!

internal class Slicer {

private var image = UIImage()
private var sliceCompletion: ((_ slices: [UIImage]) -> Void) = { _ in }

private lazy var textDetectionRequest: VNDetectTextRectanglesRequest = {

    return VNDetectTextRectanglesRequest(completionHandler: self.handleDetectedText)
}()

internal func slice(image: UIImage, completion: @escaping ((_: [UIImage]) -> Void)) {
    self.image = image
    self.sliceCompletion = completion
    self.performVisionRequest(image: image.cgImage!, orientation: .up)
}

// MARK: - Vision

private func performVisionRequest(image: CGImage, orientation: CGImagePropertyOrientation) {

    DispatchQueue.global(qos: .userInitiated).async {
        do {
            let imageRequestHandler = VNImageRequestHandler(cgImage: image, orientation: orientation, options: [:])
            try imageRequestHandler.perform([self.textDetectionRequest])
        } catch let error as NSError {
            self.sliceCompletion([UIImage]())
            print("Failed to perform vision request: \(error)")

        }
    }
}

private func handleDetectedText(request: VNRequest?, error: Error?) {
    if let err = error as NSError? {
        print("Failed during detection: \(err.localizedDescription)")
        return
    }
    guard let results = request?.results as? [VNTextObservation], !results.isEmpty else {

        noText = true
        print("Tony no text found")
        var slices = [imageNo]
        self.sliceCompletion(slices as! [UIImage])
        slices = []
        return }

    noText = false
    self.sliceImage(text: results, onImageWithBounds: CGRect(x: 0, y: 0, width: self.image.cgImage!.width, height: self.image.cgImage!.height))
}

private func sliceImage(text: [VNTextObservation], onImageWithBounds bounds: CGRect) {
    CATransaction.begin()

    var slices = [UIImage]()

    for wordObservation in text {
        let wordBox = boundingBox(forRegionOfInterest: wordObservation.boundingBox, withinImageBounds: bounds)

        if !wordBox.isNull {
            guard let slice = self.image.cgImage?.cropping(to: wordBox) else { continue }
            slices.append(UIImage(cgImage: slice))
        }
    }

    self.sliceCompletion(slices)

    CATransaction.commit()
}

private func boundingBox(forRegionOfInterest: CGRect, withinImageBounds bounds: CGRect) -> CGRect {

    let imageWidth = bounds.width
    let imageHeight = bounds.height

    // Begin with input rect.
    var rect = forRegionOfInterest

    // Reposition origin.
    rect.origin.x *= imageWidth
    rect.origin.y = ((1 - rect.origin.y) * imageHeight) - (forRegionOfInterest.height * imageHeight)

    // Rescale normalized coordinates. Tony adde + 30 to increase the size of rect
    rect.size.width *= imageWidth + 30
    rect.size.height *= imageHeight + 30

    return rect
}
}

enter image description here

标签: iosswiftxcodememory-managementmemory-leaks

解决方案


其他人告诉你的都是正确的。您有两个引用self(切片器)实例的闭包,您需要打破它们中的保留循环。我认为这条线是一个巨大的错误:

private lazy var textDetectionRequest: VNDetectTextRectanglesRequest = {
    return VNDetectTextRectanglesRequest(completionHandler: self.handleDetectedText)
}()

除了保留周期外,您没有任何收获。删除那些行!相反,只需在需要时创建匿名函数。替换这个:

try imageRequestHandler.perform([self.textDetectionRequest])

有了这个:

try imageRequestHandler.perform(
    [VNDetectTextRectanglesRequest(completionHandler:{ req, err in
        self.handleDetectedText(request:req, error:err)
    })]
)

如果仍然存在泄漏(我怀疑),则将其更改为

try imageRequestHandler.perform(
    [VNDetectTextRectanglesRequest(completionHandler:{ [weak self] req, err in
        self?.handleDetectedText(request:req, error:err)
    })]
)

推荐阅读