Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting data after a Core Data migration

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?
like image 359
fraserhess Avatar asked Jan 29 '26 10:01

fraserhess


1 Answers

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.

like image 98
Marcus S. Zarra Avatar answered Feb 01 '26 02:02

Marcus S. Zarra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!