而不是将所有模型合并到
捆绑包,我已经指定了两个模型
我想使用(模型 1 和新
模型 2 的版本)并将它们合并
使用 modelByMergingModels:
这似乎不对。为什么要合并模型?您想使用 model 2,从 model 1 迁移您的商店。
来自 NSManagedObjectModel 类参考
modelByMergingModels:
创建一个
来自现有数组的模型
模型。
您不需要对您的源模型(model 1)做任何特殊/特定的事情。只要它在您的包中,自动轻量级迁移过程就会发现并使用它.
我建议放弃您在 Xcode 中创建的映射模型,因为与自动轻量级迁移相比,我有 seen terrible performance。您的里程可能会有所不同,我在模型之间的更改与您的不同,但我不会感到惊讶。尝试在捆绑包中使用和不使用您自己的映射模型的时间。
/* 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 来指定从何处加载持久存储。