OGeek|极客世界-中国程序员成长平台

标题: objective-c - 核心数据 : How to handle new versions? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:04
标题: objective-c - 核心数据 : How to handle new versions?

我发布了一个带有 Core Data sqlite 数据库的应用程序。在我的应用程序的新版本中,我为我的 xcdatamodel 创建了一个新的“模型版本”在 XCode 中。在新版本中,删除了一个实体,并向其中一个实体添加了一些新属性。

更新到新的应用程序版本时,我收到此 sql 错误:

The model used to open the store is incompatible with the one used to create the store



我该如何处理这个错误?数据库中的所有数据都是从网上下载的,所以也许最简单的方法是在发生此错误时删除当前的sqlite文件并从头开始——但是当数据库包含无法重新生成的数据时,人们会怎么做?

解决方案:

我在 Xcode 中创建了一个映射模型,并更改了我的 persistentStoreCoordinator getter 以将选项字典处理为 addPersistentStoreWithType:configuration:URLptions:error:带 key 的方法 NSMigratePersistentStoresAutomaticallyOption .
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }

    NSURL *cacheURL = [[[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *storeURL = [cacheURL URLByAppendingPathComponent"MyDatabase.sqlite"];
    NSString *storePath = [storeURL path];

    NSError *error = nil;
    NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL optionsptions error:&error])
    {        
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    

    return __persistentStoreCoordinator;
}



Best Answer-推荐答案


您遇到的问题是您必须将数据从旧的核心数据文件迁移到新的核心数据文件。这就是您在问题中收到“不兼容”错误的原因。如果您更改核心数据模型,则需要提供旧版本和新版本,并告诉系统如何将数据从旧版本移动到新版本。

为此,您需要使用核心数据版本控制(使用包)并创建迁移方案。这是一个复杂的过程,在这个答案中可能很难解释。通常,您可以创建核心数据文件的新版本,它会自动迁移数据,但有时您可能会遇到问题。

最好的办法是在谷歌中查找核心数据版本。快速搜索会找到这个相当全面的教程 http://www.timisted.net/blog/archive/core-data-migration/ .它看起来很不错。

关于objective-c - 核心数据 : How to handle new versions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9066820/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4