Warning: Undefined array key 1 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 12
Warning: Undefined array key 2 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 15
Warning: Undefined array key 3 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 18
Warning: Undefined array key 4 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 21
Warning: Undefined array key 1 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 24
Warning: Undefined array key 2 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 27
Warning: Undefined array key 3 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 30
Warning: Undefined array key 4 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 33
Realmを使っていて、開発途中でカラムを追加したり削除したりするとアプリがクラッシュしてしまいます。
そんな時に必要なのがマイグレーションでして、今回はそのやり方を解説します。
マイグレーションのやり方
マイグレーションは、AppDelegate.swiftの didFinishLaunchingWithOptionsの中で行います。
次のように書いてください。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// マイグレーション処理
migration()
let realm = try! Realm()
return true
}
// Realmマイグレーション処理
func migration() {
// 次のバージョン(現バージョンが0なので、1をセット)
let nextSchemaVersion = 1
// マイグレーション設定
let config = Realm.Configuration(
schemaVersion: nextSchemaVersion,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < nextSchemaVersion) {
}
})
Realm.Configuration.defaultConfiguration = config
}
realmのschemaVersionは初回であればデフォルト値「0」が設定されているので、それより大きい数値(今回は1)を指定してあげれば、新しくデータベースを更新することできます。



