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

时间:2013-09-30 03:18:17

标签: ios core-data

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

在旧的datamodel中,我有一个状态为Field的Contacts表。 现在,如果状态== 2,我希望为contacts表中的每条记录创建另一个表 - “推荐”.Initmends表中的属性与Contacts表的属性完全不同。

这样做的好方法是什么。

根据我的阅读,似乎我应该使用自定义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版本没有版本标识符。即使我现在添加它们,也不会在源元数据中显示。我猜你在从模型创建商店时必须明确设置它?

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

任何想法?

1 个答案:

答案 0 :(得分:1)

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

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

相关问题