Reputation: 35
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)
{
NSLog("SUCCESS");
self.tableView.beginUpdates()
tableSection?.removeAtIndex(indexPath.row)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
self.tableView.endUpdates()
//self.getChecked()
}
}
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.
Upvotes: 0
Views: 390
Reputation: 285064
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
.
tableSection?.removeAtIndex(indexPath.row)
self.sections[self.sortedSections[indexPath.section]] = tableSection
Upvotes: 1