VladyslavPG
VladyslavPG

Reputation: 577

How to add fields to a Realm model class

My class has only 4 fields:

class List: Object {
    dynamic var name = ""
    dynamic var date = ""
    dynamic var notes = ""
    dynamic var info = ""
}

And I want to add 2 more:

dynamic var website = ""
dynamic var telephone = ""

If I add these fields to the class then Realm gives me an error due to the new fields. How can I update this class while saving all user data?

Upvotes: 3

Views: 8272

Answers (2)

Mehul
Mehul

Reputation: 602

This happens as Realm creates an internal structure with your model. Each time you need to change your model (happens quite a lot), you need to migrate your current model to new one.

The way to do this is:

  1. Make whatever changes you want to make to your Data Model
  2. Add this inside your application(application:didFinishLaunchingWithOptions:) in app delegate

    let config = Realm.Configuration(
    
       schemaVersion: 1,  //Increment this each time your schema changes
        migrationBlock: { migration, oldSchemaVersion in
    
          if (oldSchemaVersion < 1) {
                //If you need to transfer any data 
               //(in your case you don't right now) you will transfer here                                                                 
    
          }
       })
    
    Realm.Configuration.defaultConfiguration = config
    
    let realm = try! Realm()
    
  3. Now each time you change your schema, you simply add one to the schemaVersion. Of course migrations can be trickier, but for your model, this will do the trick.

For more information refer Realm Swift Documentation

Upvotes: 5

Shripada
Shripada

Reputation: 6522

There are two alternatives to consider:

  1. If your app is under development and has not been released yet, then you can delete the installed app and reinstall it. Realm will use the updated model class schema when recreating the database.

  2. If your app is already released or you otherwise want to preserve the data in the Realm file, you can gracefully upgrade the existing Realm to the new schema. You can do this by performing a migration, which instructs Realm to update the schema on the file on disk to match the model classes in your application, and gives you a chance to perform any modifications you may need to the data within the Realm file to accommodate the changes in your model classes.

Upvotes: 11

Related Questions