LoginSignup
9

More than 3 years have passed since last update.

RealmSwiftのMigration

Posted at

個人での開発中に、モデル定義を変更したところ、マイグレーションしてくれというエラーが出たため、備忘録として残しておきます。

マイグレーションとは

モデルの定義を変更したときに、データを保持したまま新しいモデル定義に適応させることをいいます。

サンプル

エラー

Realm公式に載っているコードで説明します。
すでに定義されている下記のモデルを変更してみます。

class Person: Object {
    @objc dynamic var firstName = ""
    @objc dynamic var lastName = ""
    @objc dynamic var age = 0
}

以下のように変更しました。

class Person: Object {
    @objc dynamic var firstName = ""
//ここを消しました
    @objc dynamic var age = 0
}

マイグレーションの設定を行わず、これでシュミレーターを起動すると、下記のようなエラーが出て、うまく起動しません。

Error Domain=io.realm Code=10 "Migration is required due to the following errors:
(エラー文以下省略)

解決策

AppDelegate.swiftのdidFinishLaunchingWithOptionsの部分で、マイグレーションに関する記述をしていきます。公式のコードを参照。

AppDelegate.swift
// Inside your application(application:didFinishLaunchingWithOptions:)

let config = Realm.Configuration(
    // Set the new schema version. This must be greater than the previously used
    // version (if you've never set a schema version before, the version is 0).
    //(訳)新しいスキーマのバージョンを設定。以前使っていたバージョンよりも高くなければいけない。これまでバージョンの設定をしていなければ、初期のバージョンの値は0。
    schemaVersion: 1,

    // Set the block which will be called automatically when opening a Realm with
    // a schema version lower than the one set above
    //(訳)上記のものより低いスキーマバージョンでrealmを開くときに、自動的に呼び出されるようにブロックの設定をする。
    migrationBlock: { migration, oldSchemaVersion in
        // We haven’t migrated anything yet, so oldSchemaVersion == 0
//(訳)まだマイグレーションを行っていないので、oldSchemaVersion == 0。
        if (oldSchemaVersion < 1) {
            // Nothing to do!
            // Realm will automatically detect new properties and removed properties
            // And will update the schema on disk automatically
//(訳)Realmは新しいプロパティと削除されたプロパティを自動で検知します。そして、自動でディスク上のスキーマを更新する。
        }
    })

// Tell Realm to use this new configuration object for the default Realm
//(訳)default Realmに対して、新しい設定オブジェクトを使うように、Realmに指示する。
Realm.Configuration.defaultConfiguration = config

// Now that we've told Realm how to handle the schema change, opening the file
// will automatically perform the migration
let realm = try! Realm()

最低限、スキーマがRealmによって(自動的に)アップグレードされたことを示すために、空のブロックでバージョンを更新する必要がある。

まとめ

自分は、開発の環境で、モデルの変更を行ったらschemaVersionを変更してあげています。
間違えているところがあれば、ご指摘いただけますと幸いです。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
9