核心数据迁移后插入数据 [英] Inserting data after a Core Data migration

查看:100
本文介绍了核心数据迁移后插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Core Data迁移,它引入了2种新的实体类型。迁移可以正常进行,但是我想在迁移后使用默认数据填充数据库。

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.

当前,我的方法是定义一个自定义NSEntityMigrationPolicy并覆盖endEntityMapping:manager :error:

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. 这是一个好方法吗?

  2. 为什么不调用主题的-awakeFromInsert?


推荐答案

是的,这是一个好方法;可能是目前最好的方法。

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

主题的 -awakeFromInsert 不会被调用,因为在迁移过程中未使用您的自定义子类。迁移管理器使用裸NSManagedObject而不是使用任何自定义对象来执行所有迁移操作。

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.

同样,您不应将其声明为主题 -insertNewObjectForEntityForName:inManagedObjectContext:调用实际上返回的是香草 NSManagedObject ) 。只会在代码维护期间引起混乱。

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.

这篇关于核心数据迁移后插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆