Delete/Reset all entries in Core Data?

后端 未结 30 3173
天命终不由人
天命终不由人 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:33

    Here's a version that deletes every record in every table you have.

    Swift 4

    static func resetDatabase() {
        do {
            try dataStore.persistentStoreCoordinator.managedObjectModel.entities.forEach { (entity) in
                if let name = entity.name {
                    let fetch = NSFetchRequest(entityName: name)
                    let request = NSBatchDeleteRequest(fetchRequest: fetch)
                    try mainContext.execute(request)
                }
            }
    
            try mainContext.save()
        } catch {
            print("error resenting the database: \(error.localizedDescription)")
        }
    }
    

提交回复
热议问题