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

标题: ios - coredata 通过检测版本自定义迁移 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:59
标题: ios - coredata 通过检测版本自定义迁移

我正在尝试进行自定义核心数据迁移。

在旧数据模型中,我有一个带有状态字段的联系人表。 现在,如果状态 == 2,我希望为联系人表中的每条记录创建另一个表 -“推荐”。推荐表中的属性与联系人表中的属性完全不同。

有什么好方法可以做到这一点。

从我读到的,看来我应该使用自定义 coredata 迁移策略并覆盖

- (BOOL)createDestinationInstancesForSourceInstanceNSManagedObject*)src ¬
entityMappingNSEntityMapping*)map managerNSMigrationManager*)mgr errorNSError**)error 

但是实现我想做的事情似乎太复杂了。目前我的数据模型版本为 15。我是否需要为从 1 到 14 的所有先前模型版本创建映射模型?如果我下次有版本 20 并且用户直接从版本 10 更新到版本 20,是否也会触发此迁移策略?如果出现任何问题,很难测试会发生什么。

我尝试了另一种方法 - 当我初始化 storecoordinator 时,我使用:

    NSManagedObjectModel *destinationModel = [self managedObjectModel];
    // Migration is needed if destinationModel is NOT compatible
    BOOL isMigrationNeeded = ![destinationModel isConfiguration:nil
                                    compatibleWithStoreMetadata:sourceMetadata];

    if (isMigrationNeeded) {

        self.needMigration = YES;
        DDLogInfo(@"Migration needed");

        NSArray* sourceVersionIdentifiers = [sourceMetadata objectForKey:NSStoreModelVersionIdentifiersKey];
        self.sourceMigrationVersion = [sourceVersionIdentifiers lastObject];
        DDLogInfo(@"Source Version:%@",self.sourceMigrationVersion);

        NSSet* destVersionIdentifiers = [destinationModel versionIdentifiers];
        self.destMigrationVersion = [destVersionIdentifiers anyObject];
        DDLogInfo(@"Destination Version:%@",self.destMigrationVersion);
    }

- (NSDictionary *)sourceMetadataNSError **)error
{
    return [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType
                                                                      URL:[self storeURL]
                                                                    error:error];
}

基本上,如果我检测到它正在迁移到某个版本,我会尝试比较旧模型和新模型的数据模型版本并在其他地方运行一些自定义代码。

问题是我的一些旧数据模型版本没有版本标识符。即使我现在添加它们,它也不会显示在源元数据中。我猜你必须在从模型创建商店时明确设置它?

另一种选择是忽略上述所有内容,并在执行迁移时设置并保存一个标志,并在每次启动时检查该标志。但这对我来说听起来不是很干净。

有什么想法吗?



Best Answer-推荐答案


你也可以使用一个简单的NSUserDefault。它也不会出现在旧版本中。这是一个完全可以接受的机制,并且无论如何都不是“不干净的”。

是的,您需要从第一个版本开始的所有数据模型版本,是的,从 10 到 20 的迁移将是自动的,前提是您在持久存储中启用了自动迁移。

关于ios - coredata 通过检测版本自定义迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19085963/






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