Preventing a CoreData crash for upgrading users

倖福魔咒の 提交于 2019-12-06 15:46:41

If your app is crashing in the Simulator when upgrading, your users will have crashes too.

To avoid this, you need to make sure you follow these steps:

  1. Make sure you do NOT change the original version of your data model in any way.
  2. In Xcode, select your xcdatamodel file, then from the menu choose Editor > Add Model Version...
  3. Xcode will suggest a new version name, based on the current model. Make a mental note of the new version name, then click Finish.
  4. Select the xcdatamodel file again, go to File inspector and under Model Version, select the new version name to make this your current version.
  5. In Project Navigator, select the new version of the xcdatamodel. Add your attribute.

It's important to follow these steps in this order. If you add your attribute before creating the new model or making it your current version, you will have crashes.

EDIT: This will only work if you enable lightweight migrations. This is a code snippet of how to do this:

let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]

do {
    //coordinator is an NSPersistentStoreCoordinator
    try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options
} catch var error as NSError {

  // handle error however you want here...            
  abort()
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!