-1

How to change CalendarEvent.notes to optional (nullable)?

class CalendarEvent: Object {
    @objc dynamic var date: String = ""
    @objc dynamic var notes: String = ""
    @objc dynamic var notification: String = ""
}

The Realm database is already populated with data. I want the notes property to be changed to nullable in the Realm database. If I try @objc dynamic var notes: String? = "" a runtime error appears stating Migration is required due to the following errors: - Property 'CalendarEvent.notes' has been made optional.

According to the Realm documentation, renaming a property during a migration is a way to acheive this. Is it possible to change this property to nullable and without renaming?

krichards
  • 31
  • 1
  • 7

1 Answers1

1

You can just handle this in the migration block and using the same property name is fine. Here's the code that would migrate a non-optional first_name property to an optional first_name property.

The original object looks like this

class PersonClass: Object {
    @objc dynamic var first_name = ""

and then we change the property to optional

class PersonClass: Object {
    @objc dynamic var first_name: String? = nil

and here's the migration block to do that. The first version was 1 (with the non-optional first_name) and version 2 is has the updated object.

let vers = UInt64(2)
let config = Realm.Configuration( schemaVersion: vers, migrationBlock: { migration, oldSchemaVersion in
     print("oldSchemaVersion: \(oldSchemaVersion)")
     if (oldSchemaVersion < vers) {
        print("  performing migration")

        migration.enumerateObjects(ofType: PersonClass.className()) { oldItem, newItem in
            newItem!["first_name"] = oldItem!["first_name"]
         }
     }
 })

This will leave the existing data intact. We use this kind of migration all of the time as our app needs change.

Jay
  • 34,438
  • 18
  • 52
  • 81
  • Thanks Jay, this is exactly what I was looking for – krichards Jan 24 '20 at 17:30
  • This is not working for Int or Bool. How to make an Int or a Bool property nullable? – mefahimrahman Nov 27 '22 at 07:33
  • 1
    Hi @mefahimrahman - it's been a couple of years since this post and Realm is now using Persisted vars instead of the objc, but an optional bool is defined as `@Persisted var value: Bool?` and an optional Int is `@Persisted var value: Int?`. Please see the documentation for [Supported Property Types](https://www.mongodb.com/docs/realm/sdk/swift/model-data/define-model/supported-types/#supported-property-types). We use bools and ints all the time so if it's not working for you, perhaps a posting a question with your code an a description of the issue would help. – Jay Nov 27 '22 at 14:08