ios - 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")
}
}
}
解决方案
您正在捕获对 self 的强烈引用,从而导致循环。在闭包的参数之前添加一个捕获列表 - [weak self],然后在里面可以包含
let strongself = self
然后用 strongself 替换所有对 self 的引用(即使是当前隐含的)。我不在可以轻松编辑代码的设备上,但这应该可以。
推荐阅读
- css - MailPoet:我如何固定我的定位?每次我放大和缩小时,一切都不合适。CSS
- html - 使用 [[ngModel]] 时,patchValue 不起作用
- automation - 在 TeamCity 中运行测试时获取 trx 文件未找到错误消息
- postgresql - PostgreSQL where concat 类似于 MySQL
- sql - 如何从此类表中获取每日 PV
- django - Djongo/PyMongo 不断为 Django REST 框架 API 请求创建新的数据库连接
- jquery - 构建 Vue 应用程序并使用 Bootstrap 而不包含在构建中
- reactjs - react-dropzone 中的 OnDrop 问题
- node.js - 为什么干净的纱线安装会从 yarn.lock 中删除模块?
- android - 仅创建一次时,如何将 RxJava Flowable 与函数一起使用