2016-11-14 89 views
1

重新創建它,當我推出了全新的升級,以我的應用程序實現新的核心數據實體,我的應用程序會崩潰。刪除核心數據的數據庫,並更新

如何刪除整個核心數據的數據庫,並重新創建它?我不照顧什麼在那裏,因爲數據是在應用程序加載時,經常更新的反正。它主要用於高速緩存,或者直到它可以與服務器同步。

+0

您不必刪除整個核心數據的數據庫。只需使用核心數據'Migration'來解決這個問題。 – Poles

+0

這可以幫助http://jamesonquave.com/blog/core-data-migrations-swift-tutorial/ – Poles

+0

@Poles遷移是一個容易出錯的過程,很多應用程序簡單地想要刪除表並重新開始。例如,我在Android中就是這麼做的。 –

回答

0

初始化之前您NSPersistentContainer

  • 刪除您Model.sqlite持久性存儲文件
  • 刪除在同一目錄中的所有其他文件,包含.sqlite的擴展名(Model.sqlite-shmModel.sqlite-wal)。
0

這是什麼,當我實例化我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() 
} 
+0

我可以在我的AppDelegate中調用此地址嗎?或者哪裏最好打電話給它?我沒有專用的CoreDataController。謝謝。我加了一個遷移暫時的,但我想我會需要這個未來。 – toast

+0

Personnaly我有一個獨立的類叫CoreDataController(和它的一個單例)。所有與CoreData有關的東西都進去了。這比將所有內容放在你的應用程序中更好。Delegate – CZ54

+0

但是我不必在應用程序完全加載之前調用它,否則我會得到關於不兼容db的錯誤?這就是爲什麼我想知道我是否可以在我的AppDeleage中調用這個。 – toast