IOS: deleting all Swift master data

I am a little confused about how to delete all the main data in swift. I created a button with IBAction . When I click the button, I have the following:

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

Then I mixed up with various methods to try to delete all the main data, but I can not get it to work. I used removeAll to remove from the stored array, but cannot remove from the main data. I assume I need some kind of for loop, but not sure how to do this from the request.

I tried to apply the basic principle of removing one line

 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 problem is that when I click the button, I have no indexPath value, and I also need to iterate over all the values ​​that I cannot do with the context.

+51
ios swift core-data
Jul 09 '14 at 16:06
source share
18 answers

This works for me 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'm not sure if this is the best way to do this. I also get "persistent" basic information that makes anyobject error, so if there are any solutions for this, it would be great

EDIT

Fixed by changing in bas: AnyObject

+17
Jul 09 '14 at 17:10
source share

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

 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") 
+48
Nov 26 '15 at 5:57
source share

To delete all data, you can use NSBatchDeleteRequest

 func deleteAllData(entity: String) { let ReqVar = NSFetchRequest(entityName: entity) let DelAllReqVar = NSBatchDeleteRequest(fetchRequest: ReqVar) do { try ContxtVar.executeRequest(DelAllReqVar) } catch { print(error) } } 
+23
Jul. 19 '16 at 4:38
source share

For 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) } } 
+11
Feb 02 '17 at 4:42 on
source share

For Swift 4.0 (a modified version of svmrajesh's answer ... or at least what Xcode turned into before it runs it for me.)

 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") 
+4
Mar 31 '18 at 2:47
source share

This clean () method will retrieve a list of entities from the DataModel and clear all data.

 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!

+3
Jan 18 '17 at 21:49
source share

In 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") } } 
+3
Dec 19 '17 at 5:11
source share

Here is my implementation to clear all master data in Swift 3 based on Jayant Dash, an excellent (and comprehensive) answer. This is easier thanks to support only iOS10 +. It deletes all major data objects without the need for hard coding.

 public func clearAllCoreData() { let entities = self.persistentContainer.managedObjectModel.entities entities.flatMap({ $0.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") } } 
+2
Dec 18 '17 at 20:16
source share

You can use destroyPersistentStore starting with iOS 9.0 and 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) } } } 
+2
Feb 06 '18 at 11:19
source share

An alternative would be to completely delete and recreate persistent storage (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); } 
+1
May 22 '17 at 9:37
source share

There are two simple methods, as far as I know, at first

Method 1:

Fetch, Delete, Repeat

// Initialize Fetch Request

 let fetchRequest = NSFetchRequest(entityName: "Item") 

// Set up a query for selection

  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 // ... 

}

Methode 2:

Package Removal Request

// Create a fetch request

 let fetchRequest = NSFetchRequest(entityName: "Item") 

// Create a batch delete request

  let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) do { try managedObjectContext.executeRequest(batchDeleteRequest) } catch { // Error Handling } 

I tested both and they both work great

+1
Dec 16 '17 at 11:11
source share

As above, but with a call to AppDelegte and the UIView variable used

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

Use call function

 self.deleteMessages("TimeMaster") 
0
Feb 29 '16 at 19:04
source share

I use this to delete all core data objects in 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) } } } 
0
Jan 16 '17 at 13:38 on
source share

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)") } } 
0
Jan 16 '17 at 18:14
source share

Try the following:

 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) } } 
0
Apr 22 '17 at 5:05
source share

Swift 4:

destroyPersistentStoreAtURL (_: withType: options :) will delete (or truncate) the destination persistent storage. This will safely destroy the permanent store.

Add:

 do { try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: persistentStoreURL, options: nil) } catch { // Error Handling } 

Destroy / Delete / Truncate:

 do { try persistentStoreCoordinator.destroyPersistentStoreAtURL(persistentStoreURL, withType: NSSQLiteStoreType, options: nil) } catch { // Error Handling } 

Note. The parameters in the above method must be identical to the addPersistentStoreWithType method. You must reinitiate storeCoordinator in order to use store again.

0
Jul 23 '18 at 11:36
source share

For Swift 4.0

  func deleteAllData(_ entity:String) { let managedContext = DatabaseController.getContext().persistentStoreCoordinator let context = DatabaseController.getContext() let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity) let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) do { try managedContext?.execute(batchDeleteRequest, with: context) } catch { print(error) } } 
0
Sep 27 '18 at 11:28
source share

Swift 4

IOS 9 has the ability to erase persistent storage. For better service, create an NSPersistentStoreCoordinator extension with an abstract function.

 extension NSPersistentStoreCoordinator { func destroyPersistentStore(type: String) -> NSPersistentStore? { guard let store = persistentStores.first(where: { $0.type == type }), let storeURL = store.url else { return nil } try? destroyPersistentStore(at: storeURL, ofType: store.type, options: nil) return store } } 

Destroying SQLite persistent storage then looks pretty simple:

 let coordinator = persistentContainer.persistentStoreCoordinator let store = coordinator.destroyPersistentStore(type: NSSQLiteStoreType) 



recommendations

  1. Update the destroyPersistentStore function , which does not nullify and generates specific errors, for example, a CoreDataError enumeration.
  2. Perhaps you want to update your persistent storage. To do this, you can use the addPersistentStore function NSPersistentStoreCoordinator with the extracted NSPersistentStore object from destroyPersistentStore.
0
Oct 17 '18 at 15:42
source share



All Articles