IOS Swift: Crash while deleting RowsAtIndexPaths

I get a crash when I delete a row from a tableView. Not sure what is going on. Here is my code:

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        let items = days[indexPath.row]
        self.removeItems(items, indexPath: indexPath)
    }

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return days.count
}

removeItems

func removeItems(items: [CKRecord], indexPath: NSIndexPath) {

    for item in items {
        db.deleteRecordWithID(item.recordID) { (record, error) -> Void in
            if error != nil {
                println(error.localizedDescription)
            }

            dispatch_async(dispatch_get_main_queue()) { () -> Void in
                if let index = find(exercises, item) {
                    exercises.removeAtIndex(index)
                }
            }
        }
    }

    days.removeAtIndex(indexPath.row)
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
+4
source share
1 answer

Before deleting cells (or adding), you need to call beginUpdates()on the involved tableView. Then delete or add cells. When finished, call endUpdates(). Challenge endUpdates(). Remember that after the call, endUpdates()your tableView model must match the number of sections and rows that you deleted or added. Starting and ending updates allows ui to present a whole unique animation for all cell changes.

tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
tableView.endUpdates()
+6

All Articles