我的迁移遇到了一些麻烦。 在迁移之前,我的模型中有2个表:
我需要创建一个新的实体“Category”,并将两个表的类别属性转换为一对多的关系。我还想向Food实体添加属性并创建其他实体。
我遵循的步骤如下:
1-添加模型版本并创建新的Category实体,删除类别属性,创建关系,添加新属性等...
2-使用相同的代码创建我的自定义实体迁移策略类(NSEntityMigrationPolicy的子类)
- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance
entityMapping:(NSEntityMapping *)mapping
manager:(NSMigrationManager *)manager
error:(NSError **)error {
NSLog(@"createDestinationInstancesForSourceInstance");
// Create a new object for the model context
NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:[mapping destinationEntityName] inManagedObjectContext:[manager destinationContext]];
// Ancienne catégorie
NSString* oldCategory = [sInstance valueForKey:@"categorie"];
NSLog(@"oldCategory : %@", oldCategory);
// Nouvelle catégorie
[newObject setValue:nil forKey:@"categorie"]; // Nothing for the moment
// do the coupling of old and new
[manager associateSourceInstance:sInstance withDestinationInstance:newObject forEntityMapping:mapping];
return YES;
}
3-创建映射模型
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)
我错过了什么吗?
此致 塞巴斯蒂安。
答案 0 :(得分:0)
我可能建议您只是忽略两个字符串属性(或者将其重新用于其他内容)并使用轻量级迁移,而不是在此处对自定义迁移进行故障排除(这可能很困难)。
添加商店后,您可以将旧字符串值复制到关系中,并在几行代码中将其归零。 E.g。
// 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