Ios coredata通过检测版本进行自定义迁移

Ios coredata通过检测版本进行自定义迁移,ios,core-data,Ios,Core Data,我正在尝试进行自定义coredata迁移 在旧的数据模型中,我有一个带有状态字段的联系人表。 现在,如果status==2,我希望为contacts表中的每个记录创建另一个表-“recommendas”。“推荐”表中的属性与“联系人”表中的属性完全不同 这样做的好方法是什么 从我所读到的内容来看,我似乎应该使用自定义coredata迁移策略并覆盖 - (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject*)src ¬

我正在尝试进行自定义coredata迁移

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

这样做的好方法是什么

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

- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject*)src ¬
entityMapping:(NSEntityMapping*)map manager:(NSMigrationManager*)mgr error:(NSError**)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 *)sourceMetadata:(NSError **)error
{
    return [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType
                                                                      URL:[self storeURL]
                                                                    error:error];
}
基本上,我尝试比较旧模型和新模型的datamodel版本,如果检测到它正在某个版本上迁移,则在其他地方运行一些自定义代码

问题是,我的一些旧数据模型版本没有版本标识符。即使我现在添加它们,它也不会显示在源元数据中。我猜当从模型创建存储时,您必须显式地设置它

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


有什么想法吗

您还可以使用一个简单的
NSUserDefault
。它也不会出现在旧版本中。这是一个完全可以接受的机制,绝不是“不干净”的

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