2
votes

I'm using Xcode 8 and swift 3.

I'm getting an assertion failure when I try to delete a row from a UITableView.

Assertion failure in -[UITableView _endCellAnimationsWithContext:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3599.5/UITableView.m:1610

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 (25) must be equal to the number of rows contained in that section before the update (25), 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).'

Code:

// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    // create a new cell if needed or reuse an old one
    let cell:UserCell = self.tableView.dequeueReusableCell(withIdentifier: "tblCell") as! UserCell!

    cell.titleLabel.text = self.animals[(indexPath as NSIndexPath).row]

    cell.btnDelete.addTarget(self, action:#selector(ViewController.buttonClicked(sender:)), for: UIControlEvents.touchUpInside);

    return cell
}

func buttonClicked(sender:UIButton) {
        if let superview = sender.superview {
            if let cell = superview.superview as? UserCell {
                if let indexPath = self.tableView.indexPath(for: cell){
                    print("row = ",indexPath.row)
                    self.tableView.beginUpdates()
                    self.tableView.deleteRows(at: [indexPath], with: .left)
                    self.tableView.endUpdates()
                    self.animals.remove(at:indexPath.row)
                }
            }
        }

}

I have just started learning swift so please help me.

1
the datasource must be refreshed before you end updates. Try calling self.animals.remove(at:indexPath.row) before self.tableView.endUpdates()akdsouza
@pedrouan "deleteRowsAtIndexPaths" is not there in swift 3.Ekta Padaliya

1 Answers

2
votes

try to move self.animals.remove(at:indexPath.row) before self.tableView.endUpdates() and after self.tableView.beginUpdates() I think that might solve your problem.