Reputation: 577
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
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:
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()
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
Reputation: 6522
There are two alternatives to consider:
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.
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