How to add and migrate columns without losing Realm data

Asked 2 years ago, Updated 2 years ago, 54 views

class UserClass:Object{
    dynamic variable = 0
    dynamic var user: String=""
    let colorData=List<Color>()
    override static func primaryKey()->String?{
        return "user"
    }
}

classVariousColor:Object{
    dynamic var colorData=NSData()
    letchidLink=LinkingObjects (fromType:UserClass.self, property: "data")
}

class UserClass:Object{
    dynamic variable = 0
    dynamic var user: String=""
    dynamic varkisetsu: String=""
    let colorData=List<Color>()
    override static func primaryKey()->String?{
        return "user"
    }
}

classVariousColor:Object{
    dynamic var colorData=NSData()
    letchidLink=LinkingObjects (fromType:UserClass.self, property: "data")
}

I'd like to add a column like this, but I don't know how to migrate the data used by the application on the App store.(Is it there in the first place?)

swift ios realm

2022-09-30 15:33

1 Answers

If you change the data structure of the model after release, you must migrate it.

In Realm, migration is to tell Realm that there has been a change in the data structure of the model, and to migrate the actual data from the old data structure to the new data structure.

First of all, Realm is taught that the data structure change is intentional by changing the schema version.Otherwise, Realm cannot distinguish whether the data structure is intentional or incorrectly opened the file.

The schema version is specified using the Realm.Configuration object.

let config=Realm.Configuration(schemaVersion:1)
let realm=try!Realm(configuration:config)

Create a Realm.Configuration object with schemaVersion as shown above and pass it as a parameter when instantiating Realm.

At this time, if there is no data migration from the old data structure to the new data structure, that is all.Realm automatically transforms the data structure of an existing file and copies the data to a file with a new data structure.
"Data migration" here means whether data transformation is involved.
For example, Document

 class Person: Object {
    dynamic var firstName=""
    dynamic var lastName=""
    dynamic range = 0
}

This is like converting the firstName and lastName properties into one fullName property.

 class Person: Object {
    dynamic var fullName=""
    dynamic range = 0
}

In such cases, use the migrationBlock argument to write the data conversion process.

In this case, you just added a new property called kisetsu, so you don't need to write migrationBlock because you don't think you'll have to set anything from the old data for that property.

Simply raise the schema version and open Realm to automatically add a new kisetsu property and copy the rest of the data as it is.

See the documentation for more information.
https://realm.io/jp/docs/swift/latest/ #section-40


2022-09-30 15:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.