blitz-time アプリ開発ブログ

Androidアプリ開発などのTips集

【Swift】Realm利用時に「Migration is required due to the following errors」というエラーが出る

iOSアプリ開発でRealmのインスタンス作成時に「Migration is required due to the following errors」というエラーが発生する場合があります。

realm = try Realm()
Error Domain=io.realm Code=10 "Migration is required due to the following errors:
- Property 'AlbumModel.audioProfile' has been removed.
- Property 'PlayableBaseModel.audioProfile' has been removed." UserInfo={NSLocalizedDescription=Migration is required due to the following errors:
- Property 'AlbumModel.audioProfile' has been removed.
- Property 'PlayableBaseModel.audioProfile' has been removed., Error Code=10}

上記のエラーの場合は、
AlbumModel.audioProfileが削除されました。
PlayableBaseModel.audioProfileが削除されました。
AlbumModel.audioProfileが削除されました。
PlayableBaseModel.audioProfileが削除されました。
という意味になります。

実は、このエラーが出る前に、Realmのオブジェクトのプロパティ(audioProfile)を削除しました。最終的に使用することがなかったので。

そのため、「audioProfie」が削除されました。と言われているのです。

Realmオブジェクトのプロパティを削除するということは、データベースのカラムを削除するということで、データベースの構成が変わるため、「Migration(=データベースの移行)」つまりは、「データベースのバージョンアップ」が必要ということになります。

migration対応は非常に簡単で、下記の通り、schemaVersionを設定・管理するだけです。
Realmインスタンスを作成する前に実行しましょう。

let config = Realm.Configuration(schemaVersion: 2)  // このschemaVersionを上げていく
Realm.Configuration.defaultConfiguration = config

// Realmインスタンス取得
realm = try Realm()