Delete/Reset all entries in Core Data?

后端 未结 30 3172
天命终不由人
天命终不由人 2020-11-22 16:00

Do you know of any way to delete all of the entries stored in Core Data? My schema should stay the same; I just want to reset it to blank.


Edit

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 16:20

    One other method (apart from a delete batch request) I often use (based on app requirement) is to reset the persistent store. The implementation looks like this for iOS 10+ and Swift (assuming you have a CoreDataManager class):

    let persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "“)
        container.loadPersistentStores(completionHandler: { (storeDescription, err) in
            if let err = err {
                fatalError("loading of store failed: \(err)")
            }
        })
        return container
    }()
    
    func resetPersistentStore() {
    
        if let persistentStore = persistentContainer.persistentStoreCoordinator.persistentStores.last {
            let storeURL = persistentContainer.persistentStoreCoordinator.url(for: persistentStore)
    
            do {
                try persistentContainer.persistentStoreCoordinator.destroyPersistentStore(at: storeURL, ofType: NSSQLiteStoreType, options: nil)
            } catch {
                print("failed to destroy persistent store:", error.localizedDescription)
            }
    
            do {
                try persistentContainer.persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
            } catch {
                print("failed to re-add persistent store:", error.localizedDescription)
            }
        }
    
    }
    

    One advantage of this method is that it’s more straightforward especially when you have loads of data record for numerous entities in your core data. In which case a delete batch request would be memory intensive.

提交回复
热议问题