How do I delete all objects from my persistent store in Core Data?

后端 未结 8 960
遇见更好的自我
遇见更好的自我 2020-12-01 03:59

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

相关标签:
8条回答
  • 2020-12-01 04:41

    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)
                    }
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-01 04:46
    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

    0 讨论(0)
提交回复
热议问题