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

标签 ios swift core-data

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

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.

关于ios - 如何从核心数据中永久删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28130770/

相关文章:

ios - Expo iOS 构建在启动画面上崩溃

ios - 从本地通知打开应用程序后动画标签 [Swift 3.0 - Xcode 8]

objective-c - 如果属性名称以 new 开头,应用程序会崩溃

ios - 标签栏项目不会显示

iOS:在 TableView 中添加带有过滤器选项的 UISearchbar

ios - ld : framework not found Parse Xcode 7 beta

Swift Combine - 观察 N 个对象数组中对象的属性并与其他属性合并

swift - 在类上定义存储类型属性

ios - 将值从 UITableViewCell 传递到详细信息 View

ios - 如何将从网上下载的表格加载到 iOS 中的核心数据中?