Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for property existence when running linear migration in Realm

Tags:

ios

swift

realm

I'm using the latest version of RealmSwift and encountered a fatal error when running a series of linear migrations.

The issue is that a previous migration was attempting to set the value for a property that had been removed in a later version and the particular build that was running the migrations was skipping several versions. Is there a method on RealmSwift.DynamicObject that can be used to introspect the existence of a property before attempting to set its value?

like image 774
Juan-Carlos Foust Avatar asked Oct 17 '25 09:10

Juan-Carlos Foust


2 Answers

RealmSwift.Object has an objectSchema property which describes the schema being used for that specific object. You can use this to check for the presence of a property with object.objectSchema.properties.contains { $0.name == "propName" }.

like image 71
Thomas Goyne Avatar answered Oct 19 '25 01:10

Thomas Goyne


extension Migration {
    func hadProperty(onType typeName: String, property propertyName: String) -> Bool {
        var hasPropery = false
        self.enumerateObjects(ofType: typeName) { (oldObject, _) in
            hasPropery = oldObject?.objectSchema.properties.contains(where: { $0.name == propertyName }) ?? false
            return
        }
        return hasPropery
    }

    func renamePropertyIfExists(onType typeName: String, from oldName: String, to newName: String) {
        if (hadProperty(onType: typeName, property: oldName)) {
            renameProperty(onType: typeName, from: oldName, to: newName)
        }
    }
}
like image 32
Joel Teply Avatar answered Oct 19 '25 01:10

Joel Teply