5

我正在尝试进行迁移

我有 2 个版本的模型

1.xcdatamodel
2.xcdatamodel

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

1to2.xcmappingmodel

问题是它找不到我创建的迁移模型,所以 mappingModel 总是为零。我需要做些什么来指定它应该使用的 mappingModel 吗?

target = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:modelPath]];
//target and source are initialized correctly
mappingModel = [NSMappingModel mappingModelFromBundles:nil forSourceModel:source destinationModel:target];
4

4 回答 4

5

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

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

于 2011-12-09T16:15:56.277 回答
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;
    }
于 2011-04-14T06:04:42.057 回答
0

要回答原始问题,您的代码看起来不错,但我不是您将 nil 作为 bundles 参数传递的原因。文档没有说可以。所以:

NSArray *theBundles = [NSArray arrayWithObject:[NSBundle mainBundle]];
    mappingModel = [NSMappingModel mappingModelFromBundles:theBundles
                                            forSourceModel:source 
                                          destinationModel:target];
于 2011-05-06T19:07:58.257 回答
0

如果您将 nil 作为捆绑参数传递,它将采用 [NSBundle mainBundle]。

[回应Elise van Looij的问题]

于 2012-12-20T16:07:22.983 回答