I have Core Data working in my app. So, I fetch an XML file, parse the data into model objects and insert them into core data. They are saved in the persistent store and I
swift version of @Nicolas Manzini answer:
if let psc = self.managedObjectContext?.persistentStoreCoordinator{
if let store = psc.persistentStores.last as? NSPersistentStore{
let storeUrl = psc.URLForPersistentStore(store)
self.managedObjectContext?.performBlockAndWait(){
self.managedObjectContext?.reset()
var error:NSError?
if psc.removePersistentStore(store, error: &error){
NSFileManager.defaultManager().removeItemAtURL(storeUrl, error: &error)
psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeUrl, options: nil, error: &error)
}
}
}
}
import Foundation
import CoreData
extension NSManagedObjectContext
{
func deleteAllData() {
guard let persistentStore = persistentStoreCoordinator?.persistentStores.last else {
return
}
guard let url = persistentStoreCoordinator?.url(for: persistentStore) else {
return
}
performAndWait { () -> Void in
self.reset()
do
{
try self.persistentStoreCoordinator?.remove(persistentStore)
try FileManager.default.removeItem(at: url)
try self.persistentStoreCoordinator?.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
}
catch { /*dealing with errors up to the usage*/ }
}
}
}
Thanks @Julian Krol - updated answer for Swift 5.1