LoginSignup
0
0

RealmSwift マイグレーションで古いObjectの存在しないプロパティを参照しないようにする

Posted at

RealmSwiftのマイグレーション処理の中で
古いObjectに存在しないプロパティを参照しようとすると
nilで取得できるとかじゃなくinvalid property nameエラーでクラッシュします。

migration.enumerateObjects(ofType: Sample.className(), { old, new in
    guard let old = old,
          let new = new else { return }

    // ここでクラッシュする
    guard let hoge = old["hoge"] as? String else { return } 
    
})

guard letを使っても、nilで返ってくるとかじゃないので意味がないです。

これを回避するためには以下のように
取得したいプロパティが古いObjectに存在するかチェックをしてから
取り出す必要があります。

migration.enumerateObjects(ofType: Sample.className(), { old, new in
    guard let old = old,
          let new = new else { return }
    
    if old.objectSchema.properties.contains(where: { $0.name == "hoge" }) == false {
        // 古いObjectにプロパティがない場合の処理を書く
        return
    }
    
    guard let hoge = old["hoge"] as? Bool else { return }

    // 後続処理
    
})

※ただし再現しているRealmSwiftのバージョンが4.4.1のため、
最新のバージョンでも同じ仕様かどうかは不明。

0
0
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
0
0