核心数据模型迁移步骤
问题描述:
我的迁移有一些问题。 迁移之前,我曾在我的模型2个表:核心数据模型迁移步骤
- 食物:名称(字符串),类别(字符串),等等...
- CartFood:名称(字符串),类别(字符串) etc ...
我需要创建一个新的实体“类别”,并将两个表的类别属性转换为一对多关系。我也想为Food实体添加属性并创建其他实体。
的步骤我有如下如下:
1-添加模型版本,并创建新的类别的实体,删除类别属性,建立关系,添加新的属性,等等
2-用相同的代码
3-创建我的自定义实体迁移策略类(它们是NSEntityMigrationPolicy的子类)创建映射模型
4-禁用轻量级迁移
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// Stop that right now if necessary
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
// Store URL
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"LeSecretDuPoids.sqlite"]];
// Get store
NSError *error = nil;
NSDictionary *options = @{ NSMigratePersistentStoresAutomaticallyOption : @YES, NSInferMappingModelAutomaticallyOption : @NO };
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator;
}
但是,当我推出新的应用程序,我有以下错误,没有日志显示在控制台:
CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null)
我错过了什么吗?
Regards, Sébastien。
答
与其排除自定义迁移(这可能很困难),我可能建议您忽略这两个字符串属性(或将它们重用于其他内容)并使用轻量级迁移?
添加商店后,您可以将旧的字符串值复制到关系中,并将它们排列在几行代码中。例如。
// create all necessary category objects
// fetch them and all food objects
for (Food *food in allFoodObjects) {
Category *category = [allCategories filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:@"title = %@", food.oldCategory]].firstObject;
if (category) {
food.category = category;
}
}
// repeat with cartfood
是否可以使用NSEntityMigrationPolicy子类轻量级迁移? – Seb 2015-02-13 09:04:26
如果我忽略这两个字符串,当创建新的商店时,类别关系将为空,我将无法获取旧值:/ – Seb 2015-02-13 09:05:35
不,请阅读我的答案。你必须亲自填充新的关系。但它比使用调试自定义迁移更简单。 – Mundi 2015-02-13 12:56:53