Inserting data after a Core Data migration

北战南征 提交于 2019-12-12 14:02:31

问题


I have a Core Data migration that introduces 2 new entity types. The migration works without issue, but I want to populate the database with default data after the migration.

Currently, my approach is to define a custom NSEntityMigrationPolicy and override endEntityMapping:manager:error:

- (BOOL)endEntityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError **)error {
if (![super endEntityMapping:mapping manager:manager error:error]) return NO;
Theme *defaultTheme = [NSEntityDescription insertNewObjectForEntityForName:@"Theme" inManagedObjectContext:[manager destinationContext]];
[defaultTheme setName:NSLocalizedString(@"Default", @"Default theme name")];
return YES;
}
  1. Is this a good approach?
  2. Why would Theme's -awakeFromInsert not be called?

回答1:


Yes this is a good approach; probably the best approach currently.

Theme's -awakeFromInsert is not being called because your custom subclasses are not used during migration. The migration manager performs all migration actions with bare NSManagedObject's rather than using any custom objects.

Likewise, you should not declare it as a Theme (the -insertNewObjectForEntityForName: inManagedObjectContext: call is really returning a vanilla NSManagedObject) in that method either. It will just lead to confusion during code maintenance.



来源:https://stackoverflow.com/questions/4089973/inserting-data-after-a-core-data-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!