Core Data: how to just delete and rebuild the data store?

后端 未结 3 834
逝去的感伤
逝去的感伤 2021-02-03 12:54

I\'m using Core Data in an iOS 7+ app that does not need to save user\'s data, all data the app needs is requested to services and it can be recovered at any time.

3条回答
  •  深忆病人
    2021-02-03 13:39

    Working Swift solution if you target iOS 9 or higher

    The shared CoreData manager:

    class CoreDataContext {
        static let datamodelName = "CoreDataTests"
        static let storeType = "sqlite"
    
        static let persistentContainer = NSPersistentContainer(name: datamodelName)
        private static let url: URL = {
            let url = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("\(datamodelName).\(storeType)")
    
            assert(FileManager.default.fileExists(atPath: url.path))
    
            return url
        }()
    
        static func loadStores() {
            persistentContainer.loadPersistentStores(completionHandler: { (nsPersistentStoreDescription, error) in
                guard let error = error else {
                    return
                }
                fatalError(error.localizedDescription)
            })
        }
    
        static func deleteAndRebuild() {
            try! persistentContainer.persistentStoreCoordinator.destroyPersistentStore(at: url, ofType: storeType, options: nil)
    
            loadStores()
        }
    }
    

    call loadStores only once in the appDelegate and deleteAndRebuild when you want to delete and rebuild the database :)

提交回复
热议问题