3

I am new in Swift and I want to delete all data from core data. I have seen several examples but in all of them persistentContainer is in AppDelegate and in my case persistentContainer is not in AppDelegate. It is in a different class as shown below:

class CoreDataStack: NSObject {
    
    static let sharedInstance = CoreDataStack()
    private override init() {}
    
    func applicationDocumentsDirectory() {
        if let url = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).last {
            print(url.absoluteString)
        }
    }
    lazy var persistentContainer: NSPersistentContainer = {
       
        let container = NSPersistentContainer(name: "Database")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
            print(storeDescription)
            
        })
        return container
    }()
    
    // MARK: - Core Data Saving support
    
    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

In the AppDelegate method I am just calling it as

CoreDataStack.sharedInstance.applicationDocumentsDirectory()

func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        CoreDataStack.sharedInstance.saveContext()
    }

I tried this code but it does not work for me.

halfer
  • 19,824
  • 17
  • 99
  • 186
Muju
  • 884
  • 20
  • 54

3 Answers3

10

One of the solutions can be to use NSBatchDeleteRequest for all entities in the persistentContainer. You can add these methods to your CoreDataStack:

func deleteAllEntities() {
    let entities = persistentContainer.managedObjectModel.entities
    for entity in entities {
        delete(entityName: entity.name!)
    }
}

func delete(entityName: String) {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    do {
        try persistentContainer.viewContext.execute(deleteRequest)
    } catch let error as NSError {
        debugPrint(error)
    }
}

The whole code can be found here

pawello2222
  • 46,897
  • 22
  • 145
  • 209
3

Need to use NSBatchDeleteRequest for particular entity from persistentContainer

func deleteEntityData(entity : String) {
        let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
        do {
            try CoreDataStack.sharedStack.mainContext.execute(deleteRequest)
            CoreDataStack.sharedStack.saveMainContext()
        } catch {
            print ("There was an error")
        }
}

I have detailed an answer in below link. enter link description here

Priyank Patel
  • 791
  • 8
  • 6
0

A more radical approach is to remove/recreate your persistent stores.

extension NSPersistentContainer {
    func destroyPersistentStores() throws {
        for store in persistentStoreCoordinator.persistentStores {
            let type = NSPersistentStore.StoreType(rawValue: store.type)
            try persistentStoreCoordinator.destroyPersistentStore(at: store.url!, type: type)
        }
        loadPersistentStores()
    }
    
    func loadPersistentStores() {
        loadPersistentStores { _, error in
            if let error { fatalError(error.localizedDescription) }
        }
    }
}

Usage: try container.destroyPersistentStores()

Source

parapote
  • 433
  • 2
  • 8