您如何进行初始迁移以从非 Realm 持久层迁移?

How can you have an initial migration for migrating from a non-Realm persistence layer?

我们目前正在使用 NSUserDefaults 进行数据持久化,我们想开始使用 Realm。但是,由于在添加 Realm 后首次启动时还没有当前 Realm,因此不会进行任何迁移 运行。似乎无法使用 Realm 迁移机制将此“-1”架构迁移到架构 0。

我们想这样做:

// Given that there is no Realm file
// and the app has never run this code before
RLMMigrationBlock migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
    if (oldSchemaVersion < 1) {
        // migrating NSUserDefaults to Realm
    }
};
[RLMRealm setDefaultRealmSchemaVersion:1 withMigrationBlock:migrationBlock];
[RLMRealm defaultRealm]; // this DOESN'T run the migration :(

我们已经考虑过破解方法来解决这个问题,但希望这些都不是必需的。

解决此问题的最简单方法可能是检查磁盘上是否存在默认领域,如果不存在,则访问它(这将创建 is),然后手动执行 migration