loading a store, exposing its container and deleting associated files for core data
class AppPersistentContainer {
static let sharedInstance = AppPersistentContainer()
lazy var container: NSPersistentContainer = {
self.deleteCoreDataFiles()
let container = NSPersistentContainer(name: "CozyDen")
loadPersistentStore(container:container, shouldDeleteAndRetry: true)
container.viewContext.automaticallyMergesChangesFromParent = true
return container
}()
private func loadPersistentStore(container: NSPersistentContainer, shouldDeleteAndRetry: Bool) {
container.loadPersistentStores(completionHandler: { [unowned self] (storeDescription, error) in
if let error = error as NSError? {
if (shouldDeleteAndRetry) {
print("Unresolved error \(error), \(error.userInfo)")
print("Deleting Core Data Files...")
self.deleteCoreDataFiles()
self.loadPersistentStore(container: container, shouldDeleteAndRetry: false)
return
}
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
}
private func deleteCoreDataFiles() {
let directoryURL = NSPersistentContainer.defaultDirectoryURL()
let fileManager = FileManager()
do {
let contents = try fileManager.contentsOfDirectory(atPath: directoryURL.path)
for path in contents {
let fileURL = directoryURL.appendingPathComponent(path)
do {
try fileManager.removeItem(atPath: fileURL.path)
}
catch {
print("Error deleting file \(fileURL)")
}
}
}
catch {
print("Error deleting core data files")
}
}
}