[英]Swift: Crash when loading a Table many times
我有以下问题:
在我的应用程序中,您有在线食谱,现在想象一个 TabViewController。 在此 TabViewController 的前两页上,您有一个视图,显示存储在 Firebase 实时数据库中的食谱。 在第三个中,您有一个带有一些按钮的简单视图,但没有使用和导入 Firebase。 现在的问题是,当我多次敲击底部栏并因此在一秒钟内多次切换 TabViewController 时,应用程序崩溃了。 这可能是因为 Firebase 每次都重新加载,因为 TabViewController 发生了变化,可能导致过载。
现在我收到以下错误:
Fatal error: Index out of range: file /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift, line 444
2020-05-22 16:44:28.057640+0200 GestureCook[10451:3103426] Fatal error: Index out of range: file /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift, line 444
它突出显示此代码let recipe = myRecipes[indexPath.row]
索引超出范围。 现在我怎样才能减少服务器上的负载或避免这个错误?
负载增加的原因可能是因为我必须像这个简化的示例一样一次从不同位置获取多个食谱:
// dict is a list of recipe IDs
// And the GetRecipeService.getRecipe is a service which gets a recipe using a .observeSingleEvent (this causes these requests)
for child in dict {
GetRecipeService.getRecipe(recipeUID: child.key) { recipe in
self.myRecipes.append(recipe ?? [String:Any]())
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
我怎样才能减少负载? Firebase 中是否存在多路径更新,但只是作为一个获取,所以我不必使用 a.observeSingleEvent 加载 10-20 个食谱?
首先DispatchQueue
块位于错误的位置。 它必须在封闭内
GetRecipeService.getRecipe(recipeUID: child.key) { recipe in
self.myRecipes.append(recipe ?? [String:Any]())
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
要在一个循环中管理多个异步请求,有一个 API: DispatchGroup
let group = DispatchGroup()
for child in dict {
group.enter()
GetRecipeService.getRecipe(recipeUID: child.key) { recipe in
self.myRecipes.append(recipe ?? [String:Any]())
group.leave()
}
}
group.notify(queue: .main) {
self.tableView.reloadData()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.