Search code examples
iosswiftuikiticloudcloudkit

iOS Swift: Crash on deleteRowsAtIndexPaths


I'm getting a crash when I remove a row from a tableView. Not sure what's 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)
}

Solution

  • Before removing cells (or adding) you need to call beginUpdates() on the involved tableView. Then remove, or add cells. When finished, call endUpdates(). Once you call endUpdates(). Remember that once you call endUpdates() your tableView model must be consistent with the number of sections and rows you removed or added. Begin and End updates allows the ui to present a coherent unique animation for all the cell changes.

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