簡體   English   中英

Swift應用程序在從UITableView刪除行時崩潰

[英]Swift app crashes on delete a row from 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 { }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM