Realm Migration Deleted my data from Realm


#1

0

I’ve added a new Model object to my realm objects and I am trying to move data from my old realm object properties to this new object. But the migration code I tried below, Deleted the data that was stored in Realm. Any help in the right direction would be appreciated. Thank you!

In the old Schema, I have the following:

class Item: Object {
@objc dynamic var image = “”
@objc dynamic var coverImage = “”
@objc dynamic var video = “”
}
In the new schema, I’ve added a new property called media so now it’s looking this this

class Item: Object {
@objc dynamic var image = “”
@objc dynamic var coverImage = “”
@objc dynamic var video = “”

@objc dynamic var media: Media? // new property

}
I’ve also added this new Model object:

class Media: Object { // new Object

@objc dynamic var fullImage = ""
@objc dynamic var thumbnailImage = ""
@objc dynamic var video = ""

var item = LinkingObjects(fromType: Item.self, property: "media")

}
My goal is to move the data from the old Item objects to the new Media objects.

I was trying to do something like this, but I don’t know how to migrate that linking object, any help in the right direction would be appreciated.

let config = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
// We haven’t migrated anything yet, so oldSchemaVersion == 0
if (oldSchemaVersion < 1) {

            migration.enumerateObjects(ofType: Item.className(), { (oldItem, newItem) in

                let image = oldItem?["image"] as! String
                let coverImage = oldItem?["coverImage"] as! String
                let video = oldItem?["video"] as! String

                let media = migration.create(Media.className())
                media["fullImage"] = image
                media["thumbnailImage"] = coverImage
                media["video"] = video
                newItem?["media"] = media
            })

        }
})

Realm.Configuration.defaultConfiguration = config

#2

This is a crosspost to a StackOverflow question. Not a big deal but it’s often best to keep the code, comments and answers in one spot so we don’t do double duty when providing a solution or additional info.

also, code formatting is important for readability…