1
votes

i'm trying to archive a lightweight migration with some handling after that. I already did the lightweight process and i need some help now handling my entities.

On the old model i used to have an entity "Car" and now i added the entity "Person" with the relationship Person has Cars.

So, after the lightweight migration i need to add a default person "John" and add all cars to him.

Does anyone have some idea?

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreData.sqlite"];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    NSDictionary *options = @{
                              NSMigratePersistentStoresAutomaticallyOption : @YES,
                              NSInferMappingModelAutomaticallyOption : @YES
                              };


    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}
2

2 Answers

2
votes

You can catch if a lightweight migration is going to occur. See this answer for details. There you can set a flag and based on that execute a method after normal startup in which you insert the desired entities.

Notice, though, that lightweight migration should migrate all your existing entities to the new store version, so there is usually no logically compelling reason to use this hook. Instead, you cold just query your (new or old version) store if it contains "John" and his cars and insert them if not.

0
votes

If this is a one-time upgrade to the database, it might make sense to use a custom migration policy class rather than lightweight migration. Here's a nice tutorial on customizing that process: http://9elements.com/io/index.php/customizing-core-data-migrations/

If you want to then mix inferred migration from one pair of models with custom migration between another pair of models, I've written a description of the Core Data methods involved and sample iterative migration class.