ios - 从 UITableView 删除一行时 Swift 应用程序崩溃

标签 ios swift uitableview

我知道这是一个非常简单和基本的问题,特别是对于使用 Swift 4 年的人来说,但我坚持了下来!

我正在尝试删除该行:

let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in
        do {
            self.usersTableView.beginUpdates()
            self.viewModel.users.remove(at: indexPath.row)
            self.coreDataStack.mainContext.delete(user)
            self.usersTableView.deleteRows(at: [indexPath], with: .automatic)
            self.usersTableView.endUpdates()

            try self.coreDataStack.mainContext.save()                
        } catch let error as NSError {
            print("Could not delete the user \(user) because of the \(error), \(error.userInfo)")
        }
    }

和我的

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.viewModel.users.count
}

我在尝试点击删除按钮时崩溃并出现下一个错误:

attempt to delete row 0 from section 0 which only contains 0 rows before the update

有人可以帮助我理解它是如何工作的吗?

最佳答案

从 UITableView 和 UICollectionView 中删除行的最佳有效方法是使用 PerformBatchUpdates(仅适用于 iOS 11+)

if #available(iOS 11.0, *) {
       self.usersTableView.performBatchUpdates({
             self.viewModel.users.remove(at: indexPath.row)
             self.coreDataStack.mainContext.delete(user)
             self.usersTableView.deleteRows(at: [indexPath], with: .automatic)                      
             }, completion: { (finish) in
             self.usersTableView.reloadData()         
             }) 

       }
       else { }

关于ios - 从 UITableView 删除一行时 Swift 应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51687916/

相关文章:

ios - 如果在 PayPalPaymentViewController [Paypal iOS SDK] 中选择 PaywithCard,应用程序会崩溃

ios - 带有复选框的交互式 TableView 标题

ios - 如何在 Swift 中更改滑动操作的 UITableviewCell 背景颜色?

ios - 使 UITableView 中的动态更新内容可供 VoiceOver 访问

ios - 上下滚动时 UISwitch 重置

ios - 如何在 iOS 10+ 中自定义通知的简短预览

ios - 如何从 JSON 查询中获取编码图像并将其编码为 Objective-C 中的 UIImage?

iOS 构建/ipa 创建不再适用于命令行

ios - 需要在类似最近联系人的App图标上实现3D touch

ios - 无法将 tableView 或 collectionView 中选定的图像中的 imageView 提供给详细 View