核心数据-迁移问题?

| 我正在尝试迁移 我有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];
    
已邀请:
如果您已经创建了从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;
    }
    
创建映射模型后,可能是您更改了一个模型。 即使更改似乎无关紧要,它也会更改用于查找适当映射模型的模型的哈希值。 至少我刚才被这个咬了:-)     
为了回答原始问题,您的代码看起来不错,但我不是为什么您将nil作为bundles参数传递。该文档没有说可以。所以:
NSArray *theBundles = [NSArray arrayWithObject:[NSBundle mainBundle]];
    mappingModel = [NSMappingModel mappingModelFromBundles:theBundles
                                            forSourceModel:source 
                                          destinationModel:target];
    
如果将nil作为bundle参数传递,它将采用[NSBundle mainBundle]。 [对Elise van Looij问题的答复]     

要回复问题请先登录注册