max_
max_

Reputation: 24481

Realm; making an optional attribute required in future migration

I have a Realm model which has an optional NSDate property expiryDate, which stores the date that the object will no longer be usable after.

This property needs to be changed such that the expiryDate is required. Because there are multiple versions of our app out there, I want to avoid having a function in our data layer which checks to see if the expiryDate property on each one of the objects is set, and if not, sets it to a default value.

I plan on updating our schema to replace

dynamic var expiryDate: NSDate?

with

dynamic var expiryDate: NSDate = NSDate().dateByAddingSeconds(SomeMaxExpiryDateInSeconds)

Will this change mean that all previously stored objects with an expiryDate that is not set, will be set to NSDate().dateByAddingSeconds(SomeMaxExpiryDateInSeconds) and will be saved accordingly to Realm? Or will this property be recalculated every time that it is accessed?

Upvotes: 0

Views: 1032

Answers (1)

TiM
TiM

Reputation: 15991

It's possible to change value types during a Realm migration, including between making a given property optional or non-optional. During the migration, you would have to go through and assign a value to each expiryDate object that was previously nil.

Realm.Configuration.defaultConfiguration = Realm.Configuration(
    schemaVersion: 1,
    migrationBlock: { migration, oldSchemaVersion in
        if (oldSchemaVersion < 1) {
            migration.enumerateObjects(ofType: Object.className()) { oldObject, newObject in
                if oldObject["expiryDate"] == nil {
                    newObject["expiryDate"] = Date().dateByAddingSeconds(SomeMaxExpiryDateInSeconds)
                }
            }
        }
    })

Upvotes: 1

Related Questions