Core Data versioning and migrating with custom policy

牧云@^-^@ 提交于 2019-11-28 19:01:33

Well, I did it...

My first 3 steps were correct. Continue scenario:

ADD4. Do an ItemToItemMigrationPolicy, a subclass of NSEntityMigrationPolicy. Override:

- (BOOL)beginEntityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError **)error
{
    List* list = (List*)[NSEntityDescription insertNewObjectForEntityForName:@"List" inManagedObjectContext:[manager destinationContext]];
    list.name = @"Default list";

    return YES;
}

- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance entityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError **)error
{
    Item* item = (Item*)[NSEntityDescription insertNewObjectForEntityForName:[mapping destinationEntityName] inManagedObjectContext:[manager destinationContext]];
    item.dateAdded = [NSDate date];
    task.title = [sInstance valueForKey:@"name"];

    [manager associateSourceInstance:sInstance withDestinationInstance:item forEntityMapping:mapping];

    return YES;
}

- (BOOL)createRelationshipsForDestinationInstance:(NSManagedObject *)dInstance entityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError **)error
{

    NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"List"];
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"name LIKE 'Default list'"];
    fetchRequest.predicate = predicate;

    NSError* fetchRequestError = nil;
    NSArray* listsArray = [manager.destinationContext executeFetchRequest:fetchRequest error:&fetchRequestError];
    if (fetchRequestError) {
        NSLog(@"%@", fetchRequestError.localizedDescription);
    }
    List* list = [listsArray lastObject];

    ((Item*)dInstance).list = list;

    return YES;
}

ADD5. In Xcode in mapping model set ItemToItem migration policy to custom with ItemToItemMigrationPolicy value.

ADD6. Make your new model version current and generate (replace) classes from new or changed entities.

ADD7. Do changes in your code, for example item.name no more works. Now it is item.title. Clean project and run.

If you are adding a new entity, then you will need to use a custom mapping model and turn off lightweight migration.

One important thing. When working with migration, make sure you start with a fresh example of the existing persistent store every time especially if you have had crashes. If you don't, you can corrupt the store which will cause errors to snowball.

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