在Swift 3中删除核心数据实体中的所有数据 [英] Deleting all data in a Core Data entity in Swift 3

查看:77
本文介绍了在Swift 3中删除核心数据实体中的所有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以批量删除存储在核心数据中所有实体中的所有数据?

Is there a way to do a batch delete of all data stored in all of the entities in core data?

我读到某个地方,在iOS 9或10中,苹果引入了一种批量删除的方法,但是我似乎找不到任何好的信息.

I read somewhere that in iOS 9 or 10 that apple introduced a way to do batch deletes, but I can't seem to find any good information on it.

最终,我只需要一个遍历一个实体并删除其中所有数据的函数.似乎它应该足够简单,但是事实证明,找到它的文档/教程极其困难.

Ultimately, I just need a function that goes through an entity, and deletes all of the data in it. Seems like it should be simple enough, but documentation/tutorials for it have proven exceedingly difficult to find.

有什么想法吗?

修改

我将以下代码添加到附加到按钮的IBAction中:

I added the following code into an IBAction attached to a button:

@IBAction func clearAllData(_ sender: AnyObject) {
    let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "PLProjects")
    let request = NSBatchDeleteRequest(fetchRequest: fetch)

    //get the data from core data
    getPLData()

    //reload the table view
    tableView.reloadData()
}

但是,这似乎不起作用.如果我关闭该项目并重新打开它,则数据仍然存在.我假设这也是为什么表视图不更新的原因,因为实际上并没有删除数据.

This does not seem to work however. If I close down the project and reopen it, the data is still there. I am assuming this is also why the table view doesn't update, because the data is not actually being deleted.

推荐答案

您正在考虑在iOS 9中添加的NSBatchDeleteRequest.创建这样的内容:

You're thinking of NSBatchDeleteRequest, which was added in iOS 9. Create one like this:

let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Employee")
let request = NSBatchDeleteRequest(fetchRequest: fetch)

如果只想删除与该谓词匹配的实例,则还可以添加谓词.要运行请求:

You can also add a predicate if you only wanted to delete instances that match the predicate. To run the request:

let result = try managedObjectContext.executeRequest(request)

请注意,批处理请求不会更新您当前的任何应用状态.如果您的内存中有受管理的对象可能会受到删除的影响,则需要立即停止使用它们.

Note that batch requests don't update any of your current app state. If you have managed objects in memory that would be affected by the delete, you need to stop using them immediately.

这篇关于在Swift 3中删除核心数据实体中的所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆