簡體   English   中英

內存泄漏,在do-catch塊中。 iOS,Swift

[英]Memory leak, in do-catch block. iOS, Swift

我正在查看使用視覺檢測文本的應用程序中的內存泄漏。

我收到內存泄漏,當使用樹時,該泄漏指向此行:

try imageRequestHandler.perform([self.textDetectionRequest])

我不確定為什么,希望有人可以提供幫助。

完整代碼如下。

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)")

        }
    }
}

這是整個班級:

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
}
}

在此處輸入圖片說明

其他人都告訴你的是正確的。 您有兩個引用self (Slicer)實例的閉包,並且您需要打破這兩個實例的保留周期。 我認為這行是一個巨大的錯誤:

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)
    })]
)

textDetectionRequest閉包中使用捕獲列表

lazy var textDetectionRequest: VNDetectTextRectanglesRequest = 
         { [weak self] in
             return VNDetectTextRectanglesRequest(completionHandler: self?.handleDetectedText)
         }()

我認為應該是這樣的:

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

    }
}

self.textDetectionRequestlazy var ,它捕獲handleDetectedText這是一個closure因此您應該使用[unowned self][weak self]類的捕獲列表,以避免保留周期。

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

另外,您可以將VNRequest數組作為performVisionRequest函數中的依賴項進行performVisionRequest從而簡化代碼

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

    // MARK: - Vision

    private func performVisionRequest(image: CGImage, orientation: CGImagePropertyOrientation, requests: [VNRequest]) {

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM