[英]Having trouble with crash when performing .ondelete on a list (SwiftUI).. crashing in .onReceive for a timer
I am having a problem with an app that I am making, that is crashing.我正在制作的应用程序出现问题,即崩溃。 I have been trying to hours to figure it out, but am stumped.
我一直在努力解决几个小时,但我很难过。
I have a list that holds multiple timers, that are all updated with.onReceive.我有一个包含多个计时器的列表,这些计时器都使用.onReceive 进行了更新。
I have everything working... I can start and stop each timer, reset each timer, etc. However, when I try to use.onDelete on the list to remove a timer, I get a crash with "index out of range" in the.onReceive method.我一切正常...我可以启动和停止每个计时器,重置每个计时器等。但是,当我尝试在列表中使用 .onDelete 删除计时器时,我遇到了“索引超出范围”的崩溃.onReceive 方法。
List {
ForEach(viewModel.initialTimeRemainingSeconds.indices, id: \.self) { time in
Section {
HStack {
VStack(alignment: .leading) {
Text("\(viewModel.foodName[time])")
.font(.title2.weight(.bold))
Text("\(viewModel.convertSecondsToTime(timeInSeconds: viewModel.timeRemainingSeconds[time]))")
.font(.title2)
}
Spacer()
Button {
viewModel.timeRemainingSeconds[time] = viewModel.initialTimeRemainingSeconds[time]
} label: {
Image(systemName: "gobackward")
}
.buttonStyle(PlainButtonStyle())
.frame(width: 50, height: 50, alignment: .center)
.font(.title2)
.foregroundColor(.white)
.background(.blue)
.cornerRadius(10)
Button(viewModel.timerButtonTitle[time]) {
viewModel.timerStartAndStop(timerNumber: time)
}
.buttonStyle(PlainButtonStyle())
.frame(width: 100, height: 50, alignment: .center)
.font(.title2)
.foregroundColor(.white)
.background(viewModel.timerButtonColor[time])
.cornerRadius(10)
}
.onReceive(viewModel.timer) { _ in
if viewModel.timerStart[time] == true {
viewModel.timeRemainingSeconds[time] -= 1
}
}
}
}
.onDelete { indexSet in
viewModel.deleteItem(indexSet: indexSet)
}
}
I have an array of Bools that tells the.onReceive method if the timer should start or stop.我有一个布尔数组,它告诉 .onReceive 方法是否应该启动或停止计时器。
@Published var timerStart = [Bool]()
I tried using a second ForEach inside of the.onReceive method, but that causes a crash where swift takes too long to build... I guess the ForEach happening every call of.onReceive is too much for Xcode.我尝试在 .onReceive 方法中使用第二个 ForEach ,但这会导致 swift 构建时间过长的崩溃...我猜每次调用 .onReceive 时发生的 ForEach 对于 Xcode 来说太多了。
If I comment out the.onReceive, I can delete without a crash...如果我注释掉.onReceive,我可以删除而不会崩溃...
Finally figured it out.终于想通了。 Had to change timers to scheduled timers instead of published, which allowed me to call.invalidate() on the individual timer before deleting it from the Timer array.
不得不将定时器更改为预定定时器而不是发布,这允许我在从定时器数组中删除它之前在单个定时器上调用.invalidate()。 The timer was still running for the last tick even after deleting it, giving index out of range.
即使在删除它之后,计时器仍在运行最后一个滴答声,导致索引超出范围。 Man that one was a pain.
那个男人很痛苦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.