迁移Realm中的主键

Pet*_*Pik 3 realm ios swift

我刚刚在我的Realm模型中添加了一个主键,因此我一直在低于错误.我试图在appdelegate中迁移,但仍然得到了恐怖.我所做的就是添加propertyKey()功能.我怎样才能正常迁移?

Migration is required for object type 'Organization' due to the following errors:
- Property 'id' has been made a primary key."
Run Code Online (Sandbox Code Playgroud)

但是我已经在appdelegate中添加了以下内容:

    Realm.Configuration.defaultConfiguration = Realm.Configuration(
        schemaVersion: 1,
        migrationBlock: { migration, oldSchemaVersion in
            if (oldSchemaVersion < 1) {
                // The enumerate(_:_:) method iterates
                // over every Person object stored in the Realm file
                migration.enumerate(Organization.className()) { oldObject, newObject in
                    // combine name fields into a single field

                }
            }
    })
Run Code Online (Sandbox Code Playgroud)

这是我的对象

class Location: Object {
    var id: Int = 0
    var longitude: Double = 0
    var latitude: Double = 0

    override class func primaryKey() -> String {
        return "id"
    }

}

class Organization: Object {
    var id: Int = 0
    var name: String = ""
    var image: NSData = NSData()
    let locations = List<Location>()

    override class func primaryKey() -> String {
        return "id"
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

如果Model之前没有主键,您可以通过这样做来修复它:

    //MARK: Realm Migrations
    Realm.Configuration.defaultConfiguration = Realm.Configuration(
        // bump the schema version to 2
        schemaVersion: 2,
        migrationBlock: { migration, oldSchemaVersion in
            migration.enumerate(Organization.className()) { oldObject, newObject in
                // make sure to check the version accordingly
                if (oldSchemaVersion < 2) {
                    // the magic happens here: `id` is the property you specified 
                    // as your primary key on your Model
                    newObject!["primaryKeyProperty"] = "id"
                }
            }
        }
    )
Run Code Online (Sandbox Code Playgroud)

我希望它
有所帮助,干杯!