Skipping painful migration with Core Data and move to the new data model

瘦欲@ 提交于 2019-12-05 05:29:11

问题


I'm spending a lot of time massaging core data into a new migration when I don't even care about the old data. Instead of dealing with the hassle of mapping models each time I change my data model, is there a way to just delete all existing data and jump to the new data model?


回答1:


Yep, just delete the store file and recreate it. I often (at least in development) have my code try an auto migration, and if that fails, blow away the store and start over:

// storefile is an NSURL to the store file, mom is the NSManagedObjectModel
NSError *err = nil;
NSPersistentStoreCoordinator *psc = [[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom] autorelease];
[psc addPersistentStoreWithType:NSSQLiteStoreType
                  configuration:nil
                            URL:storefile
                        options:[NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES],
                                 NSMigratePersistentStoresAutomaticallyOption,
                                 [NSNumber numberWithBool:YES],
                                 NSInferMappingModelAutomaticallyOption,
                                 nil]
                          error:&err];
if (err) // could be more specific about testing this error
{ // assume automigration failed, blow away the store and try again
  err = nil; // log it first!
  [[NSFileManager defaultManager] removeItemAtURL:storefile
                                            error:nil];
  [psc addPersistentStoreWithType:NSSQLiteStoreType
                    configuration:nil
                              URL:storefile
                          options:nil
                            error:&err];
}
// then test err again and give up if there's still a problem


来源:https://stackoverflow.com/questions/9548010/skipping-painful-migration-with-core-data-and-move-to-the-new-data-model

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