【发布时间】:2019-10-22 05:21:50
【问题描述】:
我正在使用 swift 创建一个新的 iOS 应用程序,并且需要帮助来让我的 tableView 删除数据。我正在使用 Core Data 以一对多的关系保存数据,并且我拥有它,因此选定的实体会被删除,但它在更新 tableView 时会崩溃。
我以前创建过应用程序,但这是我第一次使用一对多数据存储方法。我也用谷歌搜索了解决方案,但没有一个有效。这是我的 tableView 编辑样式的代码。
if editingStyle == .delete {
context.delete(items[indexPath.row])
do {
try context.save()
self.tableView.beginUpdates()
items.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .fade)
self.tableView.endUpdates()
} catch let error as NSError {
print("Could not save. \(error.localizedDescription)")
}
}
我希望该行与 Core Data 中的实体一起删除,但它实际上只是删除实体,然后在尝试更新 tableView 时崩溃。具体来说,我认为它在调用“deleteRows”时会崩溃,因为它会给出错误:
Project Aurora[14179:303873] *** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:第 0 节中的行数无效。更新后现有节中包含的行数( 2) 必须等于更新前该节中包含的行数 (2),加上或减去从该节插入或删除的行数(0 插入,1 删除),加上或减去移动的行数进入或退出该部分(0 移入,0 移出)。'
更多代码:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let count = fetchedRC.fetchedObjects?.count ?? 0
return count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "itemsTable", for: indexPath) as! ItemsTableViewCell
items.append(fetchedRC.object(at: indexPath))
if items[indexPath.row].isComplete == true {
let attributeString = NSMutableAttributedString(string: items[indexPath.row].name!)
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, attributeString.length))
cell.nameL.attributedText = attributeString
} else {
cell.nameL.text = items[indexPath.row].name
}
return cell
}
【问题讨论】:
-
尝试交换
item.remove...和beginUpdates行。 -
这也不起作用,我用完整的错误更新它并删除带有错误的评论以减少混乱。
-
您能出示您的
numberOfRows和cellForRow代码吗? -
@Paulw11 我用现在包含的 numberOfRows 和 CellForRow 更新了问题
标签: ios swift uitableview core-data crash