ios – Realm Swift Migration: How to see if property/key exists?


I’ve got a iOS based realm app that has gone through a number of schema changes. For one schema version (version 36), I added a property named “activationStartGameTime” as a swift TimeInterval? on a class Period. In a later schema version (version 38) I changed that property to an Int?. I have this in my migration:

if (oldSchemaVersion < 38) {
    migration.enumerateObjects(ofType: Period.className()) { oldObject, newObject in
        if let startTimeInterval = oldObject?["activationStartGameTime"] as? TimeInterval {
            newObject!["activationStartGameTime"] = Int(startTimeInterval)
        } else {
            newObject!["activationStartGameTime"] = nil
        }
    ...

For users who have received all versions of that app (specifically if they get a version of the app that has realm schema 36 or 37, they’re fine since in the property activationStartGameTime was added. However, when a user who is using a version of the app that has schema version < 36 tries to upgrade to the current app (schema version 38), they’re getting a crash because the line

        if let startTimeInterval = oldObject?["activationStartGameTime"] as? TimeInterval {

is crashing. It seems that looking for a non-existant key by using oldObject?["some_non_existant_key"] always crashes with the error:

2024-02-08 20:46:05.398426-0800 FooApp... *** Terminating app due to uncaught exception 'RLMException', reason: 'Invalid property name 'activationStartGameTime' for class 'Period'.'

I can’t seem to find the magic incantation that will let me look for a property of an oldObject and not have it crash if the property does not exist.

(I’m on realm-swift 10.46.0, which is the latest as of 2024_02_08)

Any ideas?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img