gpt4 book ai didi

ios - 试图从核心数据中删除一个实体,我得到...?

转载 作者:行者123 更新时间:2023-11-29 01:20:30 25 4
gpt4 key购买 nike

我正在尝试从核心数据中删除一个实体,但出现以下错误:

    The number of rows contained in an existing section after the update (10) must be equal to the number of rows contained in that section before the update (10), 
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).'

这是我的表格 View 函数

   // MARK: delete
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

let deletedRow:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!

if editingStyle == UITableViewCellEditingStyle.Delete {

// remove the deleted item from the model
moContext.deleteObject(scannedVisitors[indexPath.row] as NSManagedObject)
scannedVisitors.removeAtIndex(indexPath.row)
do {
try moContext.save()
print("deleted and saved")
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
// remove the deleted item from the `UITableView`
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
deletedRow.accessoryType = UITableViewCellAccessoryType.None
print("Deleted + accessory")
}

}

我在 viewDidAppear 中有 fetchRequest 而不是在 viewDidLoad 中

override func viewDidAppear(animated: Bool) {

do {
let request = NSFetchRequest(entityName: "ScannedVisitor")

scannedVisitors = try moContext.executeFetchRequest(request) as! [ScannedVisitor]

self.tableView.reloadData()

} catch let error as NSError {
print(error)
}

}

当我重新启动应用程序时,实体已被删除,但在删除操作期间我收到运行时错误。我该如何解决这个问题?

[编辑] 仔细观察我发现这部分被“解析”了 3 次

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

print("Rows \(scannedVisitors.count)")
return scannedVisitors.count
}

因为它打印

Rows 0
Rows 0
Rows 6

最佳答案

不要从 View 中获取要删除的对象,从模型中获取它并在保存上下文之前执行所有与 UI 相关的删除任务。

let objectToDelete = scannedVisitors[indexPath.row]
scannedVisitors.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:.Automatic)
moContext.deleteObject(objectToDelete)
do {
try moContext.save()
...

实际上不需要更改将要删除的单元格的附件类型

关于ios - 试图从核心数据中删除一个实体,我得到...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34662196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com