在 Swift 上删除表视图的核心数据记录(行)

Delete a coredata record(row) of a tableview on Swift

我有点卡在这里。在这里尝试了 Stack 的许多帖子和想法,但无法从 table 视图中删除内容。既不从 COREDATA 中删除记录,也不从简单的测试数组中删除记录。除此之外,代码工作正常,在 table 视图中列出数据和显示。

这是我遇到的错误:

2015-07-09 21:49:24.881 PlaygroundApp[36985:1319445] * Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-3347.44/UITableView.m:1623 2015-07-09 21:49:24.889 PlaygroundApp[36985:1319445] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.

import Foundation
import UIKit
import CoreData

class MyTableViewController: UIViewController, UITableViewDelegate {

    var cellCount = Int()
    var selectedCell = Int()
    var totalResults = Int()

    // THIS VARIABLE IS INITIALISED BY COREDATA FETCHREQUEST THEN USED TO POPULATE CELLS
    var recipients = [Float]()

    //THIS IS JUST A TEST VAR TO TEST THE TABLE VIEW DELETE
    var recipientsTeste = [1,2,3,4,5,6,7,8]


    override func viewDidLoad() {
        super.viewDidLoad()


        // FETCH COREDATA
        var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        var context: NSManagedObjectContext = appDel.managedObjectContext!
        var request = NSFetchRequest(entityName: "ConcreteEntity")
        request.returnsObjectsAsFaults = false
        var fecthResults = context.executeFetchRequest(request, error: nil)!


        //PRODUCE ARRAY FROM COREDATA
        if fecthResults.count > 0 {
            var saydir = fecthResults.count - 1
            for (var i=0; i < fecthResults.count; i++) {
                let match = fecthResults[i] as! NSManagedObject
                var tela = match.valueForKey("costAt") as! Float
                println(tela)

                recipients.append(tela)
            }

        } else {

        }

        //DEFINE # OF RECORDS AT COREDATA
        totalResults = fecthResults.count

    }

    // NUMBER OF CELLS BASED ON # OF RECORDS AT COREDATA
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

        return totalResults
    }

    // TRANSFER COREDATA RECORDS TO CELLS
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

        // LABEL CELL
        cell.textLabel?.text = "\(recipientsTeste[indexPath.row])"

        return cell

    }

    // IDENTIFY CLICKED CELLS
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        selectedCell = indexPath.row
        println(selectedCell)

        // DEFINE AN ACTION LATER TO USE THE SELECTED ROW AND CLOSE VIEW
        if indexPath.row == 0 {

            println("I clicked ZERO")
            navigationController?.popViewControllerAnimated(true)
        }
    }

    // ENABLE EDIT
    func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
        return true
    }

    // EDIT CELL

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

        //// I GET THIS INFO PRINTED CORRECTLY. IT CALLS THE METHOD FINE.
        //   println("delete indexPath \(indexPath.row)and \(recipients[indexPath.row])")

        //****************** THIS IS THE BIT THAT DOESNT WORK **********************

        switch editingStyle {
        case .Delete:

            var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            var context: NSManagedObjectContext = appDel.managedObjectContext!
            var request = NSFetchRequest(entityName: "ConcreteEntity")
            request.returnsObjectsAsFaults = false
            var fecthResults = context.executeFetchRequest(request, error: nil)!

            context.deleteObject(fecthResults[indexPath.row] as! NSManagedObject)
            fecthResults.removeAtIndex(indexPath.row)
            context.save(nil)

            tableView.reloadData()
            // remove the deleted item from the `UITableView`
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

        default:
            return

        }
        // *************************************************************************
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

}

您正在重新加载 table,这将移除您尝试删除的行,然后您再次尝试删除这些行。删除对 tableView.reloadData().

的调用
tableView.reloadData() // Delete this line

// remove the deleted item from the `UITableView`
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

编辑:您应该研究一下 NSFetchedResultsController 它是为这种事情而制作的。