在领域迁移期间删除List <T>中的类

问题描述

例如。我有旧型号,像这样:

class Foo:Object {
    @objc dynamic var id = ObjectId.generate()
    let bars = List<Bar>()
    
    override class func primaryKey() -> String? {
        return "id"
    }
}

class Bar:Object {
    @objc dynamic var id = ObjectId.generate()
    
    override class func primaryKey() -> String? {
        return "id"
    }
}

和新型号:

class Foo:Object {
    @objc dynamic var id = ObjectId.generate()
    
    override class func primaryKey() -> String? {
        return "id"
    }
}

迁移代码

let config = Realm.Configuration(
    schemaVersion: 1,migrationBlock: {migration,oldSchemaVersion in
        if oldSchemaVersion < 1 {
            migration.deleteData(forType: "Bar")
        }
    })
let realm = try! Realm(configuration: config)

运行时,错误显示“表是跨表链接列的目标”。

如果我先跑

let config = Realm.Configuration(
    schemaVersion: 1,oldSchemaVersion in
        if oldSchemaVersion < 1 {

        }
    })

然后运行

let config = Realm.Configuration(
    schemaVersion: 2,oldSchemaVersion in
        if oldSchemaVersion < 1 {

        }
        
        if oldSchemaVersion < 2 {
            migration.deleteData(forType: "Bar")
        }
    })

结果奏效。

这里是问题,这是将两次迁移合并为一次迁移的一种方法吗?

解决方法

我找到了解决方案。只需将两个迁移一起应用。

let url = Realm.Configuration().fileURL!
let schemaVersion = try! schemaVersionAtURL(url)

if schemaVersion == 0 {
    autoreleasepool {
        let configuration = Realm.Configuration(
            // Set the new schema version. This must be greater than the previously used
            // version (if you've never set a schema version before,the version is 0).
            schemaVersion: 1,migrationBlock: { migration,oldSchemaVersion in
                // We haven’t migrated anything yet,so oldSchemaVersion == 0
                if (oldSchemaVersion < 1) {
                    
                }
        })
        _ = try! Realm(configuration: configuration)
    }
    
    autoreleasepool {
        let configuration = Realm.Configuration(
            // Set the new schema version. This must be greater than the previously used
            // version (if you've never set a schema version before,the version is 0).
            schemaVersion: 2,so oldSchemaVersion == 0
                if (oldSchemaVersion < 1) {
                    
                }
                
                if (oldSchemaVersion < 2) {
                    migration.deleteData(forType: "Bar")
                }
        })
        _ = try! Realm(configuration: configuration)
    }
} else {
    let configuration = Realm.Configuration(schemaVersion: schemaVersion)
    _ = try! Realm(configuration: configuration)
}

autoreleasepool部分是必需的。否则,不会应用schemaVersion 2。