简体   繁体   中英

Swift closure memory usage

Using a closure is causing memory pressure and app to be terminated by the debugger for memory issues. Here is the simple closure I define and pass it as an argument to different functions. The memory pressure disappears if I replace the closure with two lines of code in the closure where ever it is needed. Will this closures passed to function retain outputPixelBuffer or sampleBuffer passed in the arguments indefinitely?

let videoProcessor: (CMSampleBuffer, CVPixelBuffer) throws -> Void = { (sampleBuffer, outputPixelBuffer) in
    if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer), CFGetTypeID(imageBuffer) == CVPixelBufferGetTypeID() {
        do {
            try delegate.processPixelBuffer(self, inputPixelBuffer: imageBuffer, toPixelBuffer: outputPixelBuffer)
        } catch {
            fatalError("Failed processing pixel buffer")
        }
    }
}

You're capturing a strong reference to self, causing a loop. Add a capture list - [weak self] before the parameters of the closure, then inside you can include

let strongself = self

and then replace all references to self (even currently implicit) with strongself. I'm not on a device where I can readily just edit your code, but this should do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM