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 follow
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
An alternative can be to completely remove and recreate persistent store (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);
}
Swift 4 :
destroyPersistentStoreAtURL(_:withType:options:) will delete (or truncate) the target persistent store. This will safely destroy a persistent 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 : Parameters in above method should be identical to addPersistentStoreWithType method. You need to re-initiate storeCoordinator to use store again.
Swift 5
func deleteAllData(entity: String){
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do {
let arrUsrObj = try managedContext.fetch(fetchRequest)
for usrObj in arrUsrObj as! [NSManagedObject] {
managedContext.delete(usrObj)
}
try managedContext.save() //don't forget
} catch let error as NSError {
print("delete fail--",error)
}
}
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.
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")
}
}
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.)
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")