Realm Objective-C to Swift Migration (Dynamic Migration)

136 views Asked by At

In Local Database we moved from Realm (Obj-C) to RealmSwift. After migration we have an issue in local db like all the properties were declared as Optional in Obj-C. Whereas, we used non-optional in swift db. now, we are forced to migrate entire database to new one.

we can't make manually migrate each property. like,

migrationBlock: { migration, oldSchemaVersion in
                if (oldSchemaVersion < 1) {
                    migration.enumerateObjects(ofType: User.className()) { oldObject, newObject in
                        newObject!["Id"] = oldObject!["Id"]
                    }
                }

we need a function to do migration for each property without hardcoding. Handle respective datatypes Dynamically as required.

We are trying to make dynamic function.

1

There are 1 answers

7
Vishnu On

Here is the dynamic function for realm migration,

        migrationBlock: { migration, oldSchemaVersion in
            if oldSchemaVersion < 1 {
                
                for objectSchema in migration.oldSchema.objectSchema {
                    
                    for property in objectSchema.properties {
                        
                        if property.isOptional {
                            migration.enumerateObjects(ofType: objectSchema.className) { oldObject, newObject in
                                if let oldValue = oldObject?[property.name] as? String {
                                    newObject![property.name] = String(oldValue)
                                }
                                
                                if let oldValue = oldObject?[property.name] as? Int {
                                    newObject![property.name] = Int(oldValue)
                                }
                                
                                if let oldValue = oldObject?[property.name] as? Bool {
                                    newObject![property.name] = Bool(oldValue)
                                }
                            }
                        }
                    }
                }
            }
        }