使用Core Data跳过痛苦的迁移并转移到新的数据模型

bee*_*lez 2 cocoa core-data objective-c core-data-migration

当我甚至不关心旧数据时,我花了很多时间将核心数据按摩到新的迁移中.每次我更改数据模型时,有没有办法只删除所有现有数据并跳转到新数据模型,而不是处理映射模型的麻烦?

rge*_*rge 5

是的,只需删除商店文件并重新创建即可.我经常(至少在开发中)让我的代码尝试自动迁移,如果失败,吹走商店并重新开始:

// 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
Run Code Online (Sandbox Code Playgroud)