Yoam Farges
Yoam Farges

Reputation: 773

Primary key update in Realm migration

I have several cases where I have to update some object models, including the property that I use as a primary key.

For example :

But of course the documentation clearly states that :

Once an object with a primary key is added to a Realm, the primary key cannot be changed

You can always remove old objects and create new ones, but this would add a lot of complexity to re-create the relationships.

And I'm pretty sure realm may not be happy with the identifier type change either way (judging by the thrown exceptions that I encountered).

So I was wondering if there was a simpler way to do so, or if I had to do a lot of manual grunt work to achieve my very simple goals.

Upvotes: 0

Views: 2159

Answers (1)

kishikawa katsumi
kishikawa katsumi

Reputation: 10573

Katsumi from Realm here. Realm supports primary key migration. Primary keys can be changed only during migration. So you'd like to change the existing primary key values, you can write migration block, then you can assign new values for each new objects. The values must be unique of course.

let config = Realm.Configuration(schemaVersion: 1, migrationBlock: { (migration, schemaVersion) in
    migration.enumerateObjects(ofType: "Person", { (oldObject, newObject) in
        newObject!["key"] = ...
    })
})

You can change primary key type as well. In that case, you also need to write a migration block and assign new values. Because the primary key property is cleared when changing the type. Also, you can merge or split existing primary key property. You can add a new property, then specify it as a primary key, then you also should write migration block and assign new unique values as well.

However, the latest version of Realm (2.8.0 and 2.8.1) made unintentional bug that doesn't allow to modify primary key even during migration. So if you're urgent, you should use the previous version (2.7.x), if you are not urgent, please wait to be fixed the bug in next release.

Upvotes: 3

Related Questions