如何从核心数据中永久删除对象?

How can I permanently delete an object from core data?

我正在构建一个应用程序,它使用数据来保存对象,然后获取结果以将它们存储在一个数组中,该数组显示在 table 视图中。我添加了一个函数,以便用户可以从 table 视图中删除一行,我还添加了一个函数,以便它从核心数据中删除对象。它在一定程度上起作用,当我在模拟器上测试它时,该行被删除(它不会崩溃)并且我可以导航到其他视图控制器然后返回到 table 视图......该行我删了好像核心数据也删了。当我停止模拟器然后重新启动它时,问题就来了。我返回到 table 视图,我删除的行再次出现,就好像它还在内存中一样。作为一名新程序员,我不确定这是否是模拟器的问题,它是否会在实际设备上按预期工作,或者我的代码是否无法工作。有经验的人可以告诉我这是模拟器问题还是我做错了什么,伙计们干杯!

var myList: Array<AnyObject> = []

override func viewWillAppear(animated: Bool) {

    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext!
    let freq = NSFetchRequest(entityName: "ToDoList")        

    myList = context.executeFetchRequest(freq, error: nil)!
}


//This is where I think something is going wrong
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    let appDeleg: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let contexts: NSManagedObjectContext = appDeleg.managedObjectContext!

    if editingStyle == UITableViewCellEditingStyle.Delete {

        if let tblview = self.tableView {

            contexts.deleteObject(myList[indexPath.row] as NSManagedObject)
            myList.removeAtIndex(indexPath.row)
            tblview.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
            self.tableView.reloadData()

        }

    }

}

确保您在某些时候使用 contexts.save() 保存您的 NSManagedObjectContext 否则您的更改将不会在应用程序启动之间持续存在。您可以在 applicationDidEnterBackground 中或在某些情况下在您的应用程序逻辑中执行保存。由于保存可能是一项昂贵的操作,因此请事先检查 hasChanges。苹果文档说:

Always verify that the context has uncommitted changes (using the hasChanges property) before invoking the save: method. Otherwise, Core Data may perform unnecessary work.