ios - 核心数据删除问题

标签 ios swift core-data

我有以下代码可以从 Core Data 中删除一条记录:

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){
        if (editingStyle == UITableViewCellEditingStyle.Delete) {

            let recordToDelete = varUserClients[indexPath.row]

            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

            let managedContext = appDelegate.managedObjectContext

            managedContext.deleteObject(recordToDelete)

                do {
                    try managedContext.save()

                } catch let error as NSError  {

                    NSLog("Could not save \(error), \(error.userInfo)")
            }

            clientsTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)

            clientsTableView.reloadData()
        }
    }

代码成功删除了记录,但它也使应用程序崩溃。其他一切正常。我在这里做错了什么?

PS:这是我收到的错误信息:

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

PPS:根据@GeneratorOfOne 的要求,这是其余代码:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return varUserClients.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let IndividualCell = clientsTableView.dequeueReusableCellWithIdentifier("ClientCell", forIndexPath: indexPath) as! CUSTOMCLIENTS

        let client = varUserClients[indexPath.row]

        let varFirstName = client.valueForKey("clientsFirstName") as! String
        let varLastName = client.valueForKey("clientsLastName") as! String
        let varFullName = String("\(varFirstName) \(varLastName)")

        IndividualCell.outletLabel_UserClientFullName.text = varFullName

        IndividualCell.outletLabel_UserClientPhoneNumber.text = (client.valueForKey("clientsMobilePhoneNumber") as! String)

        IndividualCell.outletLabel_UserClientEmailAddress.text = (client.valueForKey("clientsWorkEmailAddress") as! String)

        IndividualCell.outletLabel_UserClientPosition.text = (client.valueForKey("clientsJobTitle") as! String)

        IndividualCell.outletLabel_UserClientDistributionList.text = (client.valueForKey("clientsDistributionList") as! String)

        let varSelectPriorityPic = client.valueForKey("clientsDistributionList") as! String
        switch varSelectPriorityPic {
        case constRiskMatrixCodeLevel01:
            IndividualCell.outletImage_UserClientDistributionListImage.image = UIImage(named: "clientpriority1")
        case constRiskMatrixCodeLevel02:
            IndividualCell.outletImage_UserClientDistributionListImage.image = UIImage(named: "clientpriority2")
        case constRiskMatrixCodeLevel03:
            IndividualCell.outletImage_UserClientDistributionListImage.image = UIImage(named: "clientpriority3")
        case constRiskMatrixCodeLevel04:
            IndividualCell.outletImage_UserClientDistributionListImage.image = UIImage(named: "clientpriority4")
        case constRiskMatrixCodeLevel05:
            IndividualCell.outletImage_UserClientDistributionListImage.image = UIImage(named: "clientpriority5")
        default:
            break
        }
        return IndividualCell
    }

最佳答案

您还必须从数据源数组中删除该项。

我建议先从数据源(模型)和 TableView ( View )中删除项目,然后再删除核心数据中的项目。

重要说明:deleteRowsAtIndexPaths 会自动重新排序表格。您不得调用 reloadData()

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){
    if (editingStyle == UITableViewCellEditingStyle.Delete) {

        let recordToDelete = varUserClients[indexPath.row]
        varUserClients.removeAtIndex(indexPath.row)
        clientsTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)

        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext
        managedContext.deleteObject(recordToDelete)
        do {
           try managedContext.save()
        } catch let error as NSError  {
           NSLog("Could not save \(error), \(error.userInfo)")
        }
    }
}

关于ios - 核心数据删除问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34925670/

相关文章:

ios - 如何仅存储没有时区和实际时间的日期

ios - scanForPeripheralWithServices 不返回任何东西

cocoa-touch - 在索引 501 处获取的对象有一个乱序的部分名称 'JOURNAL OF APPLIED PHYSICS. Objects must be sorted by section name'

sqlite - 使用Sqlite和Unicode字符串的CoreData无法获取

arrays - 快速获取 double 组的总和

ios - RestKit 仅在 Post/Put 上映射多个根对象

ios - 用于多部分表单上传的 AFNetworking 2.0 API

ios - 如何隐藏这个后退按钮?

objective-c - 如何在 NSViewController.transition 期间将 NSViewController 固定到 NSPopover 的顶部?

swift - Swift 中具有约束的 SKSpriteNode 的随机向下运动