mark96 mark96 - 1 year ago 125
iOS Question

Swift TableView deleteRowsAtIndexPaths NSException

I have a dynamic TableView and want to delete rows with an animation.

My Code:

struct TableItem {
let text: String
let id: String
let creationDate: String
let bug: String
let comments: String
var sections = Dictionary<String, Array<TableItem>>()
var sortedSections = [String]()

//Some other Code

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {


override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {

let setChecked = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Erledigt" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
var tableSection = self.sections[self.sortedSections[indexPath.section]]
let tableItem = tableSection![indexPath.row]

//Not important HTTP POST Code

if(success == 1)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left)


return [setChecked]

If I run this Code I get the following error-message:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 6. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (2), 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).'

I have no idea what I'm doing wrong.

Thanks for your help.

Answer Source

That's the value type trap.

Swift collection types are structs which have value semantics unlike classes which have reference semantics.

The line var tableSection = self.sections[self.sortedSections[indexPath.section]] makes a copy of the object and leaves self.sections unchanged.

After removing the item from the list you have to assign the array back to self.sections.

self.sections[self.sortedSections[indexPath.section]] = tableSection
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download