Got a weird RLMException: Invalid property name 'primaryKeyProperty' for class


I have been using Realm for quite a long time and in about 3 - 4 versions ago I have added primaryKey to an old object.
The migration block looks like this:

Realm.Configuration(encryptionKey: REALM_KEY,
                                         schemaVersion: 3,
                                         migrationBlock: {
                                            migartion, oldSchemaVersion in
                                            if oldSchemaVersion < 2 {
                                                migartion.enumerateObjects(ofType: DBObject.className(), {
                                                    oldObject, newObject in
                                                    newObject?["primaryKeyProperty"] = "dbReferenceID"
                                         deleteRealmIfMigrationNeeded: false)

The migration has been working fine until today that I have received a crash log from the client showing the following problem:

Fatal Exception: RLMException
Invalid property name 'primaryKeyProperty' for class 'DBObject'.

I am wondering if I have mis-used the migration to add primaryKey to old object, but I have tested using old version of my application which works fine.


Does that crash occur within the migration block or perhaps within the DBObject class

override static func primaryKey()



The crash occur within the migration block.


Looking at your code, there’s an issue which may or may not be intentional.

newObject?["primaryKeyProperty"] = "dbReferenceID"

That won’t work; primary keys must be unique and assigning “dbReferenceID”` to each object would be a duplicate.

Let’s assume though, you just used that as a placeholder in your question.

I created a Car object with a color property and added them to realm

I then updated my Car object like this

class CarObject: Object {
    @objc dynamic var color = ""
    @objc dynamic var primaryKeyProperty = ""
    override static func primaryKey() -> String? {
        return "primaryKeyProperty"

and then tested it with the following migration block

Realm.Configuration.defaultConfiguration = Realm.Configuration(
    schemaVersion: 1,
    migrationBlock: { migration, oldSchemaVersion in
        if (oldSchemaVersion < 1) {
            migration.enumerateObjects(ofType: CarObject.className()) { oldObject, newObject in
                newObject?["primaryKeyProperty"] = NSUUID().uuidString

and it worked correctly and added the NSUUID().uuidString primary key to each car object.