首页 > 解决方案 > Swift 闭包内存使用

问题描述

使用闭包会导致内存压力和应用程序因内存问题而被调试器终止。这是我定义的简单闭包并将其作为参数传递给不同的函数。如果我用闭包中需要的两行代码替换闭包,内存压力就会消失。传递给函数的这个闭包是否会无限期地保留outputPixelBuffer或传递参数?sampleBuffer

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

标签: iosswiftclosures

解决方案


您正在捕获对 self 的强烈引用,从而导致循环。在闭包的参数之前添加一个捕获列表 - [weak self],然后在里面可以包含

let strongself = self

然后用 strongself 替换所有对 self 的引用(即使是当前隐含的)。我不在可以轻松编辑代码的设备上,但这应该可以。


推荐阅读