ios - 将 RxSwift.Observable 的“compactMap”从闭包重构为函数后的内存泄漏
问题描述
我发现我的代码中可能存在泄漏,因为单元测试测试是否在以下位置调用了依赖项deinit
:
func testDeinit_ShouldStopMinutesTicker() throws {
let minutesTicker = MockMinutesTicker(elapsedTicksAfterStart: [(), (), ()])
var viewModel: AppointmentViewModel? = createAppointmentViewModel(minutesTicker: minutesTicker)
viewModel = nil
XCTAssertTrue(minutesTicker.isStopCalled)
}
这个测试通常是绿色的。但是当我重构这个时:
func selectAppointment(index: Int) {
selectedCellParamRelay.accept(index)
}
private func setupCellParamSelection() {
selectedCellParamRelay
.withLatestFrom(sortedCellParams) { ($0, $1) }
.compactMap { [weak self] index, cellParams in
guard let `self` = self,
let selectedParam = cellParams[safe: index],
self.isUpcomingAppointment(selectedParam) else { return nil }
return selectedParam
}
.bind(to: upcomingCellParamRelay)
.disposed(by: disposeBag)
}
进入这个:
func selectAppointment(index: Int) {
selectedCellParamRelay.accept(index)
}
private func setupCellParamSelection() {
selectedCellParamRelay
.withLatestFrom(sortedCellParams) { ($0, $1) }
.compactMap(selectAppointment(index:from:))
.bind(to: upcomingCellParamRelay)
.disposed(by: disposeBag)
}
private func selectAppointment(
index: Int,
from cellParams: [AppointmentCellParam]
) throws -> AppointmentCellParam? {
guard let selectedParam = cellParams[safe: index],
isUpcomingAppointment(selectedParam) else { return nil }
return selectedParam
}
private func isUpcomingAppointment(_ appointment: AppointmentCellParam) -> Bool {
return appointment.status != .missed && appointment.status != .finished
}
它变成红色并且deinit
根本不被调用。
setupCellParamSelection
正在调用 func以init
设置事件处理程序以按索引选择任何约会单元格。这sortedCellParams
是一个由依赖项发出的中继,该依赖项又会从后端获取值。
你能帮我弄清楚第二个代码出了什么问题吗?
谢谢。
解决方案
是的,因为即使函数不需要 self 也.compactMap(selectAppointment(index:from:))
需要保持self
才能调用。selectAppointment
这里的解决方案是移动isUpcomingAppointment(_:)
到selectAppointment(index:from:)
类之外或作为类中的静态函数。
推荐阅读
- mysql - 从删除外键的表中选择会导致 ProgrammingError: 1146, "Table
不存在” - html - 如何使 div 仅从左右四舍五入?
- c# - CS1503:参数 3:无法从“double”转换为“UnityEngine.Quaternion”帮助!unity 2D c#
- firebase - 在 Firestore 中检索嵌套子集合的文档 ID
- python - BeautifulSoup4 将输出 find_all() 一个一个地打印为数组
- python - 如何更改 discord.py 中的帮助命令
- minecraft - Minecraft - 使用命令方块让生物敌对其他生物
- c# - 外键的类属性
- javascript - 为什么使用二进制图像发起 jQuery POST 请求比使用 Base64 编码的等价物要慢?
- python - 从 sql 文件或使用 csv 文件将数据插入 mysql