LoginSignup
3
2

Realmのエラー解決法:Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=10 "Migration is required due to the following errors:

Posted at

Realmのデータ構造を変更した際に起こったエラー

Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=10 "Migration is required due to the following errors:

  • Property 'Item.name' has been added." UserInfo={Error Name=SchemaMismatch, NSLocalizedDescription=Migration is required due to the following errors:
  • Property 'Item.name' has been added., Error Code=10}

内容としては、後からデータ構造にプロパティ「Item.name」が追加されたのに、マイグレーション処理ができてませんというエラーです!

原因

変更前のデータ構造

Item.swift
import Foundation
import RealmSwift

class Item: Object {
    @Persisted var title: String = ""
    @Persisted var done: Bool = false
    @Persisted var order = 0
}

変更後のデータ構造

Item.swift
import Foundation
import RealmSwift

class Item: Object {
    @Persisted var title: String = ""
    @Persisted var done: Bool = false
    @Persisted var order = 0
    @Persisted var name: String = ""
}

後からデータ構造にプロパティ「Item.name」が追加されたのにマイグレーション処理ができていないことが原因でエラーが起こりました!
既に保存されている情報と新規で操作しようとしている情報が違いますよというエラーです!

解決方法

Realmのデータ構造を変更したらマイグレーション処理が必要になる!
まだAppStoreにリリースしていないアプリのRealmのデータ構造を変更した後、シミレータで確認したい場合であれば、下記の方法で解決できます!

command + shift + H で下記の画像のホームに行き、アプリのアイコンを長押しすることで、削除ボタンが出てきます!削除ボタンを押して一度アプリを削除します!

シミュレータを実行したらエラーが解消しました!
※既にリリースしたアプリは、ユーザーにアプリを削除して入れ直してということにはいかないので、マイグレーション処理を書く必要があるので注意が必要です!

参考文献

3
2
0

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
  3. You can use dark theme
What you can do with signing up
3
2