【问题标题】:Skipping painful migration with Core Data and move to the new data model使用 Core Data 跳过痛苦的迁移并迁移到新的数据模型
【发布时间】:2012-03-21 19:47:39
【问题描述】:

当我什至不关心旧数据时,我花费了大量时间将核心数据按摩到新的迁移中。每次更改数据模型时,不必处理映射模型的麻烦,有没有办法删除所有现有数据并跳转到新数据模型?

【问题讨论】:

    标签: objective-c cocoa core-data core-data-migration


    【解决方案1】:

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

    // 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
    

    【讨论】:

    • 啊哈,这行得通,谢谢。在开发中我经常只是删除应用程序,但在生产中这不是一个好方法:)
    • 您是否顺利发布了此代码?我即将提交使用类似方法的应用程序。
    • 嗯。我不得不承认我做到了(至少类似的代码。)该应用程序可以在需要时快速重建其数据库,并且让它这样做比设置映射模型更快+更便宜。
    • @kukudas 我使用它发布了我的代码,效果很好。我让它寻找“旧”文件名,如果找到,删除并创建一个新的 MOMD。否则,使用现有的“新” MOMD 文件
    猜你喜欢
    • 2010-10-09
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 2014-07-07
    相关资源
    最近更新 更多