【问题标题】:Swift: Crash when loading a Table many timesSwift:多次加载表格时崩溃
【发布时间】:2020-05-22 15:08:49
【问题描述】:

我有以下问题:

在我的应用程序中,您有在线食谱,现在想象一个 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 中是否有诸如多路径更新的东西,但只是作为一个获取,所以我不必使用 .observeSingleEvent 加载 10-20 个食谱?

【问题讨论】:

    标签: ios swift firebase performance multipath


    【解决方案1】:

    首先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()
    }
    

    【讨论】:

    • 谢谢!就是这样!很高兴知道...现在该错误仅在您真正猛击 TabBarViewController 时出现,这完全没问题...
    • 这将延迟整个过程,直到所有加载我认为操作更好使用performBatchUpdates
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多