iosswiftswift3realm

How to add new property to a Realm Object?


I am trying to add a new property to the Realm object UserDetails. Here is my try:

class CustomerDetails: Object {
   dynamic var customer_id = 0
   dynamic var customer_name = ""
}

Now i need to add a new property "company_name" to the object UserDetails which is already being created earlier. How to add a new one to the existing Realm object?


Solution

  • Two ways to do it:

    1. Just delete your app from simulator and run it again. Everytime you change properties on your Realm objects your existing database becomes incompatible to the new one. As long as you are still in the developing stage you can simply delete the app from the simulator / device and start it again.

    2. Write this code in AppDelegate's disFinishLaunchWithOptions method:

    let config = Realm.Configuration(
         schemaVersion: 1,
            migrationBlock: { migration, oldSchemaVersion in
            if (oldSchemaVersion < 1) {
                // Nothing to do!
                // Realm will automatically detect new properties and removed properties
                // And will update the schema on disk automatically
            }
    })
    
    Realm.Configuration.defaultConfiguration = config
    let realm = try! Realm()
    
    

    I suggest you to follow the second one.