简体   繁体   English

在领域之间复制对象时需要迁移

[英]Migration required when copying objects between Realms

I'm trying to copy objects between two Realm databases. 我正在尝试在两个Realm数据库之间复制对象。 The first database's schema is version 0 and the second is version 1. 第一个数据库的架构是版本0,第二个数据库是版本1。

        let backupConfig = Realm.Configuration(
            path: "\(tmp)/ReadingLog.realm", // This Realm is version 0
            readOnly: true
        )

        let backupRealm = try! Realm(configuration: backupConfig)
        let defaultRealm = try! Realm() // My default Realm is version 1

        let books = backupRealm.objects(Book)

        try! defaultRealm.write {
            for book in books {
                defaultRealm.create(Book.self, value: book, update: true)
            }
        }

When I replace my current Realm database file with the old one the migration works perfectly. 当我用旧文件替换当前的Realm数据库文件时,迁移可以正常进行。 But if instead of replacing the files I try to copy objects between them I get "migration is required for object" etc. 但是,如果我没有替换文件而不是尝试在它们之间复制对象,则会收到“对象需要迁移”等信息。

I tried stating the paths, schemaVersions and migrationBlocks explicitly in every configuration, but it doesn't matter. 我尝试在每种配置中明确说明路径,schemaVersions和migrationBlocks,但这并不重要。

What am I doing wrong? 我究竟做错了什么?

Thanks in advance, 提前致谢,

Daniel 丹尼尔

Ok, after a while going through the migration example I managed to sort it out. 好的,经过一段时间的迁移示例后,我设法进行了排序。

I had to add my new schemaVersion (1) to the configuration of the old Realm database, which seems a little counter intuitive to me: 我必须将新的schemaVersion(1)添加到旧的Realm数据库的配置中,这对我来说似乎有点不直观:

        let backupConfig = Realm.Configuration(
            path: "\(tmp)/ReadingLog.realm", // This file is version 0
            readOnly: true,
            schemaVersion: 1 // But I have to set this to version 1
        )

I thought schemaVersion should be this database's version, so Realm would know from what version to migrate, but actually it seems to be the new version I want it to migrate to . 我认为schemaVersion应该是该数据库的版本,因此Realm会知道要从哪个版本进行迁移,但实际上它似乎是我希望将其迁移版本。

Then I had to call migrateRealm(backupConfig) right after that. 然后,我必须在此之后立即调用migrateRealm(backupConfig) And then it worked! 然后它起作用了!

So here's the working code: 所以这是工作代码:

        let backupConfig = Realm.Configuration(
            path: "\(tmp)/ReadingLog.realm",
            readOnly: true,
            schemaVersion: 1
        )
        migrateRealm(backupConfig)

        let backupRealm = try! Realm(configuration: backupConfig)
        let defaultRealm = try! Realm()

        let books = backupRealm.objects(Book)

        try! defaultRealm.write {

            for book in books {
                defaultRealm.create(Book.self, value: book, update: true)
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM