iOS:删除所有核心数据Swift

对于如何快速删除所有核心数据,我有点困惑。 我创build了一个IBAction链接的button。 点击button我有以下几点:

 let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate let context: NSManagedObjectContext = appDel.managedObjectContext 

然后我搞砸了各种方法试图删除所有的核心数据内容,但我似乎无法得到它的工作。 我已经使用removeAll从存储数组中删除,但仍然不能从核心数据中删除。 我假设我需要某种types的循环,但不确定如何去请求。

我曾尝试应用删除单行的基本原则

 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() } } } 

然而,这个问题是,当我点击一个button,我没有indexPath值,也需要循环所有的值,我似乎无法做上下文。

试试这个简单的解决

 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)") } } 

执行:

  self.deleteAllData("your_entityName") 

我已经得到它使用以下方法工作:

 @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) } } 

但是,我不确定这是否是最好的方法。 我也收到一个'不变的'基'推断有任何对象'的错误 – 所以如果有任何解决scheme,那么这将是伟大的

编辑

通过更改为bas:AnyObject来修复

要删除所有可以使用NSBatchDeleteRequest的数据

 func deleteAllData(entity: String) { let ReqVar = NSFetchRequest(entityName: entity) let DelAllReqVar = NSBatchDeleteRequest(fetchRequest: ReqVar) do { try ContxtVar.executeRequest(DelAllReqVar) } catch { print(error) } } 

对于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) } } 

这个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) } } } } 

快乐编码!

另一种方法是彻底删除并重新创build持久存储(iOS 10+,swift 3)。

 let urls = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask); var dbUrl = urls[urls.count-1]; dbUrl = dbUrl.appendingPathComponent("Application Support/nameOfYourCoredataFile.sqlite") do { try persistentContainer.persistentStoreCoordinator.destroyPersistentStore(at: dbUrl, ofType: NSSQLiteStoreType, options: nil); } catch { print(error); } do { try persistentContainer.persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: dbUrl, options: nil); } catch { print(error); } 

我使用这个来删除Swift3中的所有核心数据实体

 func deleteAllCD(){ for entityName in ["EntityName", "AnotherEntityName"]{ let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName) let delAllReqVar = NSBatchDeleteRequest(fetchRequest: request) do { try persistentContainer.viewContext.execute(delAllReqVar) } catch { print(error) } } } 

Swift 3

 // Replace 'MyEntityName' with your managed object class. let moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let fetchRequest: NSFetchRequest<MyEntityName> = MyEntityName.fetchRequest() fetchRequest.returnsObjectsAsFaults = false moc.perform { do { let myEntities = try fetchRequest.execute() for myEntity in myEntities { moc.delete(myEntity) } try moc.save() } catch let error { print("Delete Error: \(error.localizedDescription)") } } 

与上面类似,但是使用AppDelegte调用并使用了UIViewvariables

 var context: NSManagedObjectContext? //deleting Message func deleteMessages(entity: String) { do { let request = NSFetchRequest(entityName: entity) print(request) if let result = try context!.executeFetchRequest(request) as? [your class of NSManagedObject] { for message in result { context!.deleteObject(message) try context!.save() print(message) self.tableView.reloadData() } } } catch { print("miss") } } 

使用通话function

 self.deleteMessages("TimeMaster") 

尝试这个:

 func deleteAllData(entity: String) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let ReqVar = NSFetchRequest(entityName: entity) let DelAllReqVar = NSBatchDeleteRequest(fetchRequest: ReqVar) do { try ContxtVar.executeRequest(DelAllReqVar) } catch { print(error) } }