删除Core Data数据库,并在更新时重新创建它

时间:2016-11-14 11:36:24

标签: ios swift core-data

当我推出新的升级到我的应用程序实现新的Core Data实体时,我的应用程序将崩溃。

如何删除整个Core Data数据库并重新创建?我不关心那里的什么,因为数据通常会在应用程序加载时更新。它主要用于缓存,或者直到它可以与服务器同步。

2 个答案:

答案 0 :(得分:1)

在初始化NSPersistentContainer之前:

  • 删除Model.sqlite持久性商店文件
  • 删除同一目录中包含.sqliteModel.sqlite-shmModel.sqlite-wal)中wordcloud(cleanFullCorpus, max.words = 100, random.order = FALSE, colors=brewer.pal(10,'Spectral')) 的所有其他文件。

答案 1 :(得分:1)

这是我在实例化CoreDataController时使用的:

private override  init() {
    // This resource is the same name as your xcdatamodeld contained in your project.

    guard let modelURL = NSBundle(forClass:CoreDataController.classForCoder()).URLForResource("YOURAPP", withExtension:"momd") else {
        fatalError("Error loading model from bundle")
    }
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    guard let mom = NSManagedObjectModel(contentsOfURL: modelURL) else {
        fatalError("Error initializing mom from: \(modelURL)")
    }
    let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
    self.managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    self.managedObjectContext.persistentStoreCoordinator = psc
    let storeURL = CoreDataController.storeUrl
    do {
        try psc.addPersistentStoreWithType(CoreDataController.storeType(), configuration: nil, URL: storeURL, options: nil)
    } catch { //Exception means your database leads to error, so drop it, and create a new one
        do {
            try NSFileManager.defaultManager().removeItemAtURL(storeURL)
            try psc.addPersistentStoreWithType(CoreDataController.storeType(), configuration: nil, URL: storeURL, options: nil)}
        catch {
            fatalError("Error migrating store: \(error)")
        }

    }
    super.init()
}