Deleting all data in a Core Data entity in Swift 3

后端 未结 3 1841
孤独总比滥情好
孤独总比滥情好 2021-01-31 15:58

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

I read somewhere that in iOS 9 or 10 that apple introduced a way to do batch

3条回答
  •  轮回少年
    2021-01-31 16:15

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

    let fetch = NSFetchRequest(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.

提交回复
热议问题