Swift TableView deleteRowsAtIndexPaths NSException
问题描述:
我有一个动态的TableView,并希望用动画删除行。Swift TableView deleteRowsAtIndexPaths NSException
我的代码:
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]
}
如果我运行此代码我收到以下错误消息:
终止应用程序由于未捕获的异常“NSInternalInconsistencyException”,理由是:“无效的更新:数无效行(第6节)。更新(2)后,现有节中包含的行数必须等于更新前(2)节中包含的行数,加上或减去插入或删除的行数该部分(0插入,1删除)和加或减去移入或移出该部分的行数(0移入,0移动已出)。'
我不知道我在做什么错。
感谢您的帮助。
答
这就是值类型陷阱。
Swift集合类型是具有值语义的结构,与具有引用语义的类不同。
该行var tableSection = self.sections[self.sortedSections[indexPath.section]]
复制了该对象并使self.sections
保持不变。
从列表中删除项目后,您必须将阵列重新指定为self.sections
。
tableSection?.removeAtIndex(indexPath.row)
self.sections[self.sortedSections[indexPath.section]] = tableSection
谢谢!现在一切正常。 – mark96