问题
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;
}
- Is this a good approach?
- 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