Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Delete ALL Core Data Swift

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:

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.

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.

like image 648
Prateek Avatar asked Jul 09 '14 16:07

Prateek


People also ask

How do I delete all Core Data?

One approach to delete everything and reset Core Data is to destroy the persistent store. Deleting and re-creating the persistent store will delete all objects in Core Data.

How do I delete Core Data in Swift 4?

Table views have a built-in swipe to delete mechanic that we can draw upon to let users delete commits in our app. Helpfully, managed object context has a matching delete() method that will delete any object regardless of its type or location in the object graph.

What is Persistentcontainer in Core Data?

NSPersistentContainer simplifies the creation and management of the Core Data stack by handling the creation of the managed object model ( NSManagedObjectModel ), persistent store coordinator ( NSPersistentStoreCoordinator ), and the managed object context ( NSManagedObjectContext ).

What is delete rule in Core Data?

A delete rule defines what happens when the record that owns the relationship is deleted. Select the notes relationship of the Category entity and open the Data Model Inspector on the right. By default, the delete rule of a relationship is set to nullify. Core Data supports four delete rules: No Action.


2 Answers

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") 
like image 51
Rajesh Loganathan Avatar answered Sep 20 '22 17:09

Rajesh Loganathan


You can use destroyPersistentStore starting in 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 {          print("Attempted to clear persistent store: " + error.localizedDescription)      } } 
like image 20
gogoslab Avatar answered Sep 21 '22 17:09

gogoslab