[英]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.