Search code examples
iosswiftmigrationrealm

Migrate Realm 2.x List of Object to Realm 3.x List of String (or other primary type)


Realm 3.0 introduces List of primitives types (String, Int, …).

I'd like to migrate old Lists of custom object containing only one property of a primitive type to those simpler lists, but I don't understand how during the Realm migration block.

What I used in Realm 2.0 (simplified):

class Map: Object {
  let cities = List<City>()
}

class City: Object {
  @objc dynamic var name: String = ""

  override static func indexedProperties() -> [String] {
    return ["name"]
  }
}

What I'd like to use in Realm 3.0:

class Map: Object {
  let cities = List<String>()

  override static func indexedProperties() -> [String] {
    return ["cities"]
  }
}

How to do the migration? The following doesn't work.

if oldSchemaVersion < 2 {
  migration.enumerateObjects(ofType: Map.className(), { (oldObject, newObject) in
    newObject!["cities"] = oldObject!["cities"] as! List<String>
  })
}

Not sure about the use of indexedProperties() as well with those new lists.


Solution

  • You will need to convert the list of Cities to a list of Strings:

    if oldSchemaVersion < 2 {
      migration.enumerateObjects(ofType: Map.className(), { (oldObject, newObject) in
        newObject!["cities"] = (oldObject!["cities"] as! List<MigrationObject>).value(forKey: "name")
      })
    }
    

    Indexing List properties is not supported.