核心数据 - 迁移问题?

ary*_*axt 5 iphone core-data objective-c core-data-migration mapping-model

我正在尝试进行迁移

我有2个版本的模型

1.xcdatamodel
2.xcdatamodel
Run Code Online (Sandbox Code Playgroud)

我创建了从版本1到2的映射模型

1to2.xcmappingmodel
Run Code Online (Sandbox Code Playgroud)

问题是它无法找到我创建的迁移模型,因此mappingModel始终为nil.有什么我必须做的,以指定它应该使用什么mappingModel?

target = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:modelPath]];
//target and source are initialized correctly
mappingModel = [NSMappingModel mappingModelFromBundles:nil forSourceModel:source destinationModel:target];
Run Code Online (Sandbox Code Playgroud)

Tho*_*ten 5

可能是您在创建映射模型后更改了其中一个模型.

即使更改似乎不相关,它也会更改用于查找适当映射模型的模型的哈希值.至少我刚才被这个咬了:-)


wes*_*der 4

如果您已经创建了从 1.xcdatamodel 到 2.xcdatamodel 的映射模型,并正确配置了它,那么您应该能够执行如下操作: [注意:关键是指定NSMigratePersistentStoresAutomaticallyOption ]

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
    {
    if (persistentStoreCoordinator)
        return persistentStoreCoordinator;

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"MyStore.sqlite"]];

    NSError *error = nil;
   persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, nil];

   if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 
                                        configuration:nil
                                        URL:storeUrl
                                        options:options
                                        error:&error])
        {
        // Handle error
        NSLog(@"Error adding persistent store...%@", error);
        // Handle the error. 
        NSLog(@"Failed to save to data store: %@", [error localizedDescription]);
        NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
        if(detailedErrors != nil && [detailedErrors count] > 0)
            {
            for(NSError* detailedError in detailedErrors)
                {
                NSLog(@"  DetailedError: %@", [detailedError userInfo]);
                }
            }
        else
            {
            NSLog(@"  %@", [error userInfo]);
            }

        }
    else
        {
        DLog(@"Persistent store added without incident, apparently.");
        }

    return persistentStoreCoordinator;
    }
Run Code Online (Sandbox Code Playgroud)