iOS:删除所有核心数据 Swift
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24658641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS: Delete ALL Core Data Swift
提问by Prateek
I am a little confused as to how to delete all core data in swift. I have created a button with an IBAction
linked. On the click of the button I have the following:
我对如何快速删除所有核心数据感到有些困惑。我创建了一个带有IBAction
链接的按钮。单击按钮时,我有以下内容:
let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
Then I've messed around with various methods to try and delete all the core data content but I can't seem to get it to work. I've used removeAll to delete from a stored array but still can't delete from the core data. I assume I need some type of for loop but unsure how to go about making it from the request.
然后我尝试了各种方法来尝试删除所有核心数据内容,但我似乎无法让它工作。我已经使用 removeAll 从存储的数组中删除,但仍然无法从核心数据中删除。我假设我需要某种类型的 for 循环,但不确定如何从请求中实现它。
I have tried applying the basic principle of deleting a single row
我试过应用删除单行的基本原则
func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
if editingStyle == UITableViewCellEditingStyle.Delete {
if let tv = tblTasks {
context.deleteObject(myList[indexPath!.row] as NSManagedObject)
myList.removeAtIndex(indexPath!.row)
tv.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
}
var error: NSError? = nil
if !context.save(&error) {
abort()
}
}
}
However, the issue with this is that when I click a button, I don't have the indexPath value and also I need to loop through all the values which I can't seem to do with context.
但是,问题在于当我单击一个按钮时,我没有 indexPath 值,而且我需要遍历所有我似乎无法处理上下文的值。
采纳答案by Prateek
I have got it working using the following method:
我使用以下方法让它工作:
@IBAction func btnDelTask_Click(sender: UIButton){
let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "Food")
myList = context.executeFetchRequest(request, error: nil)
if let tv = tblTasks {
var bas: NSManagedObject!
for bas: AnyObject in myList
{
context.deleteObject(bas as NSManagedObject)
}
myList.removeAll(keepCapacity: false)
tv.reloadData()
context.save(nil)
}
}
However, I am unsure whether this is the best way to go about doing it. I'm also receiving a 'constant 'bas' inferred to have anyobject' error - so if there are any solutions for that then it would be great
但是,我不确定这是否是最好的方法。我也收到了一个推断有任何对象的“常量 bas”错误 - 所以如果有任何解决方案,那就太好了
EDIT
编辑
Fixed by changing to bas: AnyObject
通过更改为 bas 修复:AnyObject
回答by Rajesh Loganathan
Try this simple solution:
试试这个简单的解决方案:
func deleteAllData(entity: String)
{
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedContext.executeFetchRequest(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.deleteObject(managedObjectData)
}
} catch let error as NSError {
print("Detele all data in \(entity) error : \(error) \(error.userInfo)")
}
}
Swift 4
斯威夫特 4
func deleteAllData(_ entity:String) {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do {
let results = try dataController.viewContext.fetch(fetchRequest)
for object in results {
guard let objectData = object as? NSManagedObject else {continue}
dataController.viewContext.delete(objectData)
}
} catch let error {
print("Detele all data in \(entity) error :", error)
}
}
Implementation:
执行:
self.deleteAllData("your_entityName")
回答by Sujay U N
To Delete all data you can use NSBatchDeleteRequest
要删除所有数据,您可以使用 NSBatchDeleteRequest
func deleteAllData(entity: String)
{
let ReqVar = NSFetchRequest(entityName: entity)
let DelAllReqVar = NSBatchDeleteRequest(fetchRequest: ReqVar)
do { try ContxtVar.executeRequest(DelAllReqVar) }
catch { print(error) }
}
回答by anshul king
For Swift 3.0
为了 Swift 3.0
func DeleteAllData(){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let DelAllReqVar = NSBatchDeleteRequest(fetchRequest: NSFetchRequest<NSFetchRequestResult>(entityName: "Entity"))
do {
try managedContext.execute(DelAllReqVar)
}
catch {
print(error)
}
}
回答by gogoslab
You can use destroyPersistentStore
starting in iOS 9.0and Swift 3:
您可以destroyPersistentStore
从iOS 9.0和Swift 3开始使用:
public func clearDatabase() {
guard let url = persistentContainer.persistentStoreDescriptions.first?.url else { return }
let persistentStoreCoordinator = persistentContainer.persistentStoreCoordinator
do {
try persistentStoreCoordinator.destroyPersistentStore(at:url!, ofType: NSSQLiteStoreType, options: nil)
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url!, options: nil)
} catch let error {
print("Attempted to clear persistent store: " + error.localizedDescription)
}
}
}
回答by riherd
For Swift 4.0(modified version of svmrajesh's answer… or at least what Xcode turned it into before it would run it for me.)
对于 Swift 4.0(svmrajesh 答案的修改版本……或者至少 Xcode 在它为我运行之前把它变成了什么。)
func deleteAllData(entity: String) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedContext.fetch(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.delete(managedObjectData)
}
} catch let error as NSError {
print("Delete all data in \(entity) error : \(error) \(error.userInfo)")
}
}
Implementation:
执行:
deleteAllData(entity: "entityName")
回答by Amul4608
In Swift 3.0
在 Swift 3.0 中
func deleteAllRecords() {
//delete all data
let context = appDelegate.persistentContainer.viewContext
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "YourClassName")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try context.execute(deleteRequest)
try context.save()
} catch {
print ("There was an error")
}
}
回答by Jayant Dash
This clean() method will fetch entities list from DataModel and clear all data.
此 clean() 方法将从 DataModel 中获取实体列表并清除所有数据。
func deleteAll(entityName: String) -> Error? {
if #available(iOS 9.0, *) {
do {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
try context.execute(batchDeleteRequest)
} catch {
return error
}
return nil
} else {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try context.fetch(fetchRequest)
for managedObject in results
{
if let managedObjectData:NSManagedObject = managedObject as? NSManagedObject {
context.delete(managedObjectData)
}
}
} catch {
return error
}
return nil
}
}
var objectModel: NSManagedObjectModel? {
if #available(iOS 10.0, *) {
return persistentContainer.managedObjectModel
} else {
return persistentStoreCoordinator?.managedObjectModel
}
}
open func clean() {
if let models = objectModel?.entities {
for entity in models {
if let entityName = entity.name {
_ = deleteAll(entityName: entityName)
}
}
}
}
Happy Coding!
快乐编码!
回答by rmooney
Here is my implementation to clear all core data in Swift 3, based on Jayant Dash's excellent (and comprehensive) answer. This is simpler due to only supporting iOS10+. It deletes all core data entities, without having to hardcode them.
这是我根据 Jayant Dash 出色(且全面)的答案清除 Swift 3 中所有核心数据的实现。由于仅支持 iOS10+,因此更简单。它删除所有核心数据实体,而无需对其进行硬编码。
public func clearAllCoreData() {
let entities = self.persistentContainer.managedObjectModel.entities
entities.flatMap({ let fetchRequest = NSFetchRequest(entityName: "Item")
.name }).forEach(clearDeepObjectEntity)
}
private func clearDeepObjectEntity(_ entity: String) {
let context = self.persistentContainer.viewContext
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try context.execute(deleteRequest)
try context.save()
} catch {
print ("There was an error")
}
}
回答by raddaoui
There are two simple methods as far as i know , first
据我所知,有两种简单的方法,首先
Method 1:
方法一:
Fetch, Delete, Repeat
获取、删除、重复
// Initialize Fetch Request
// 初始化获取请求
fetchRequest.includesPropertyValues = false
do {
let items = try managedObjectContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
for item in items {
managedObjectContext.deleteObject(item)
}
// Save Changes
try managedObjectContext.save()
} catch {
// Error Handling
// ...
// Configure Fetch Request
// 配置获取请求
let fetchRequest = NSFetchRequest(entityName: "Item")
}
}
Methode 2:
方法二:
Batch Delete Request
批量删除请求
// Create Fetch Request
// 创建获取请求
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try managedObjectContext.executeRequest(batchDeleteRequest)
} catch {
// Error Handling
}
// Create Batch Delete Request
// 创建批量删除请求
##代码##I have tested both and they both work fine
我已经测试了它们,它们都可以正常工作