Search code examples
realmswift4realm-migration

Check if previous Realm Object contains new column


I checked online but I can't find much to help me. Basically we're planning to have an "emergency" release of our app due to crashes in the Realm - we forgot to create a migration for a new property.

migration.enumerateObjects(ofType: Pet.className(), {oldObject, newObject in
    newObject?[“nickname”] = nil
}

Since this is an "emergency" release some users already have the "nickname" property and if the code above runs this field will be changed to nil. Thus we would like to check if the "nickname" property already exists in the oldObject so we can retain the value.

EDIT: I tried oldObject?["nickname"] == nil this works find for those users that already has the nickname property. But I encounter NSException for the users that doesn't have yet the nickname property.

Anyone knows how to do it? Thanks!


Solution

  • I think I found an answer for myself:

    migration.enumerateObjects(ofType: Pet.className(), {oldObject, newObject in
        let hasNicknamePropery = oldObject?.objectSchema.properties.contains(where: { $0.name == "nickname" }) ?? false
        if !hasNicknamePropery {
            newObject?[“nickname”] = nil
        }
    }
    

    I just check the schema of the oldObject and check if the "nickname" property is already exists.