jbehrens94
jbehrens94

Reputation: 2406

Realm included in bundle doesn't migrate

I have created a Realm database with the data I needed at the moment, but I need to add two properties to an entity. Therefore, I just added those two properties to my entity. I expected a crash, because of pending migrations, so I created an extra migration. Now, these changes I made don't show up in my Realm database on my filesystem.

The code I use to migrate is the following:

func migrate() {
    let defaultPath = Realm.Configuration.defaultConfiguration.fileURL!
    let realmPath = Bundle.main.url(forResource: "compactedNulTien", withExtension: "realm")

    if let bundledRealm = realmPath {
      do {
        try FileManager.default.removeItem(at: defaultPath)
        try FileManager.default.copyItem(at: bundledRealm, to: defaultPath)
      } catch {}
    }

    let config = Realm.Configuration(schemaVersion: 4, migrationBlock: { migration, oldSchema in
      if oldSchema < 1 {
        migration.enumerateObjects(ofType: PointOfInterest.className(), { (old, new) in
          new!["index"] = 0
        })
      } else if oldSchema < 2 {
        migration.enumerateObjects(ofType: PointOfInterest.className(), { (old, new) in
          new!["place"] = ""
        })
      } else if oldSchema < 3 {
        migration.enumerateObjects(ofType: PointOfInterest.className(), { (old, new) in
          new!["contentImage"] = ""
          new!["contentExtension"] = ""
        })
      }
    })
    Realm.Configuration.defaultConfiguration = config

    do {
      realm = try Realm()
    } catch(let error) {
      Crashlytics().recordError(error)
    }

}

This is how I have the realm file in my project, so I expected that one to be upgraded. How do I get the new properties in my local realm database so I can fill them?

Realm situation

Upvotes: 0

Views: 87

Answers (1)

jbehrens94
jbehrens94

Reputation: 2406

Right, I forget (probably) that the .realm is copied again to the Documents folder in the Simulator. So I picked it from there with help from print(realm.configuration.fileURL ?? "No URL Found") call. I exported it again to a compacted version, filled it and then I've replaced in Xcode, ran the app again, migrations worked fine, done.

Upvotes: 1

Related Questions