swiftsqlitecore-dataxcdatamodel

Process to change data model


How to change the .xcdatamodeld file i.e. the data model?

Since the program has already been run and the Persistent Store Coordinator (PSC) contains a url to .sqlite, .sqlite-shm and .sqlite-wal files on disk I think the process is as follows but am unsure. Any input would be appreciated.

  1. Run code below to delete the url from PSC.
  2. Delete sqlite files from disk.
  3. Change .xcdatamodeld file.
  4. CodeGen is set to manual so create new managed object subclasses.
  5. Make appropriate changes to code.
  6. Run program which I assume will enter a url into the PSC and create the 3 sqlite files on disk but now based on the new .xcdatamodeld file.
func deletePersistentStore() {
    guard let persistentStoreURL = container.persistentStoreCoordinator.persistentStores.first?.url
    else {
        print("URL Missing")
        return
    }
    do {
        try container.persistentStoreCoordinator.destroyPersistentStore(
            at: persistentStoreURL,
            ofType: "SQLite",
            options: nil)
    } catch  {
        print("Persistent Store Not Deleted: \(error) - \(error.localizedDescription)")
    }
    print("\(container.persistentStoreCoordinator.persistentStores.count)")
    // prints 0
    print("\(String(describing: container.persistentStoreCoordinator.persistentStores.first?.url) )")
    // prints nil
}

Solution

  • It sounds like you’re still developing this app and that it’s not released yet. If that’s true, you could do something like this. But it would be easier to delete the app from your phone (or simulator), change the model, and then install a new copy of the app.

    That would let you skip steps 1 and 2.

    If your app is already released, you should look into Core Data model migration. It’s a process that lets you update the data model without deleting existing data. In most cases it’s nearly automatic, but it depends on how much your model is changing.