如何在 table 视图中重新加载数据而不会在 swift 3 中崩溃?

how to Reload data on table view without crashing in swift 3?

我的应用程序中有一个 TableView,当用户点击其中一个单元格中的按钮时,safari 将在应用程序中打开,当 safari 关闭时,应用程序将崩溃,因为我想更新其中的一个参数tableview 所以我需要从 Json 中删除所有并再次附加它们但这将需要几秒钟所以应用程序将崩溃因为没有数据显示我使用了计时器但计时器不是好的解决方案因为有时它会花费比计时器更多的时间所以它会再次崩溃我需要一个等待完成然后做其他事情的方法如果你认为这也不是一个好的解决方案请指导我哪个解决方案适合这个问题

这是我在应用程序中关闭 safari 后在我的应用程序中使用的内容(不是所有代码,但这些代码有问题)

 if let payed = dict.value(forKey: "payed"){

                            factorViewController.payed.removeAll()
                            self.factorTableView.reloadData()
                            factorViewController.payed.append(payed as! Int)
                            self.factorTableView.reloadData()

                            print("payed = \([payed])")

                        }

尝试只重新加载一次数据:

 if let payed = dict.value(forKey: "payed") {
     // Empty Array here
     factorViewController.payed.removeAll()
     // You are appending here, so array will not be empty
     factorViewController.payed.append(payed as! Int)
     // Now you can reload data
     self.factorTableView.reloadData() 
     print("payed = \([payed])")
     // Also, if this doesn't work, you can use a callback(completion handler).
 }

这样,当你需要重新加载数据时,你的数组就不会为空

TableView 的工作原理

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return your_array.count // It returns how much cells you want in your tableview.
    }

 // This func defines what you wanted in your cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = dequeue_property // to dequeue your cell
     your_lbl.text = your_array[indexpath.row] // as per logic
    return cell
} 

你的情况

numberOfRowsInSection 中数组的数量比您在 cellForRowAt 中使用的数组多.这就是为什么没有获得索引并使用 IndexOutOFRange

崩溃的原因

你有数组问题而不是 tableView 重新加载问题

参考:

好的,这比我想象的要容易!我刚刚在我的应用程序中定义了另一个变量,当开始获取 Json 时,将新数据附加到新变量,然后将新变量等于旧变量!就是这样!