0

Application part deletes the file but also crashes on error message

declared part

var FileContent = (try? FileManager.default.contentsOfDirectory(atPath : newpath.first!))
var SingleUrl = newpath.first!
//MARK:- viewcontroller extension Deleting file from directory
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
    try! FileManager.default.removeItem(atPath: SingleUrl + "/" + FileContent![indexPath.row])
    self.tableView.deleteRows(at: [indexPath], with: .fade)
    }

the error message is............

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (5), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

ManDeep
  • 15
  • 3
  • Reload the table view after deleting a row. – El Tomato Jan 08 '20 at 10:32
  • Does this answer your question? [Deleting a Row from a UITableView in Swift 3?](https://stackoverflow.com/questions/40156274/deleting-a-row-from-a-uitableview-in-swift-3) – dahiya_boy Jan 08 '20 at 10:34
  • start var names with small letter – Shehata Gamal Jan 08 '20 at 10:37
  • 1
    You should delete element from the respective datasource(array) as well! – Ketan Parmar Jan 08 '20 at 10:42
  • Check your number of rows in section method , you are returning wrong number of rows that's what the message shows. And one should first call tableView.beginUpdates & after updates tableView.EndUpdates.The original data model from which you are returning numberof Rows is not updated. That model is still returning the original number of rows (5) because you have not removed that item from that array – Help Jan 08 '20 at 11:12
  • @Help No, one should **not** call `begin-/endUpdates` for a single delete operation. It's only for multiple simultaneous insert/delete/move operations. – vadian Jan 08 '20 at 12:11

1 Answers1

0

You need to delete from the array not only the file

try! FileManager.default.removeItem(atPath: singleUrl + "/" + fileContent![indexPath.row]) 
fileContent!.remove(at:indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .fade)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87