iOS: Delete ALL Core Data Swift
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")
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) }
}
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)
}
}
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
EDIT
Fixed by changing to bas: AnyObject