我没有合并捆绑包中的所有模型,而是指定了我要使用的两个模型(模型 1 和模型 2 的新版本)并使用 modelByMergingModels 合并它们:
这似乎不对。为什么要合并模型?您想使用模型 2 ,从模型 1迁移您的商店。
来自 NSManagedObjectModel 类参考
modelByMergingModels:
从现有模型数组创建单个模型。
您不需要对源模型(模型 1)做任何特殊/特定的事情。只要它在您的包中,自动轻量级迁移过程就会发现并使用它。
我建议放弃您在 Xcode 中创建的映射模型,因为与自动轻量级迁移相比,我已经看到了糟糕的性能。您的里程可能会有所不同,我在模型之间的更改与您的不同,但我不会感到惊讶。在捆绑包中尝试使用和不使用您自己的映射模型的时间。
/* Inferred mapping */
NSError *error;
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,nil];
NSPersistentStore *migratedStore = [persistentStoreCoordinator addPersistentStoreWithType:nil
configuration:nil
URL:self.storeURL
options:options
error:&error];
migrationWasSuccessful = (migratedStore != nil);
您可以在代码中验证您的源模型是否可用,方法是尝试加载它并验证它不是 nil:
NSString *modelDirectoryPath = [[NSBundle mainBundle] pathForResource:@"YourModelName" ofType:@"momd"];
if (modelDirectoryPath == nil) return nil;
NSString *modelPath = [modelDirectoryPath stringByAppendingPathComponent:@"YourModelName"];
NSURL *modelFileURL = [NSURL fileURLWithPath:modelPath];
NSManagedObjectModel *modelOne = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelFileURL];
if (modelOne == nil) {
NSLog(@"Woops, Xcode lost my source model");
}
else {
[modelOne release];
}
这假设在您的项目中,您有一个资源“ YourModelName.xcdatamodeld ”和“ YourModelName.xcdatamodel ”。
此外,您可以检查该模型是否与您现有的迁移前持久存储兼容:
NSError *error;
NSDictionary *storeMeta = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:nil URL:self.storeURL error:&error];
if (storeMeta == nil) {
// Unable to read store meta
return NO;
}
BOOL isCompatible = [modelOne isConfiguration:nil compatibleWithStoreMetadata:storeMeta];
该代码假定您有一个方法-storeURL
来指定从何处加载持久存储。