はじめに
Realmでオブジェクを設定して、途中で変更をするとクラッシュしてしまいます。
これに対応するには「マイグレーション」と言うものが必要らしいです。
Realmでのマイグレーションの方法を学んだので記録しておきます。
元のオブジェクト
import Foundation
import RealmSwift
class SampleObject: Object {
@Persisted(primaryKey: true) public var id: Int = 0
}
新しいオブジェクト
import Foundation
import RealmSwift
class SampleObject: Object {
@Persisted(primaryKey: true) public var primaryKey: Int = 0
}
実装
import Foundation
import RealmSwift
class SampleRealmRepository {
func get() throws -> Results<SampleObject> {
+ Realm.Configuration.defaultConfiguration = config
return try! Realm().objects(SampleObject.self)
}
func add(object: SampleObject) throws {
+ Realm.Configuration.defaultConfiguration = config
let realm = try Realm()
try realm.write {
realm.add(object)
}
}
func delete(object: SampleObject) throws -> Results<SampleObject> {
+ Realm.Configuration.defaultConfiguration = config
let realm = try Realm()
if let history = realm.object(ofType: SampleObject.self, forPrimaryKey: object.primaryKey) {
try realm.write {
realm.delete(object)
}
}
return realm.objects(SampleObject.self)
}
func deleteAll() throws -> Results<SampleObject> {
+ Realm.Configuration.defaultConfiguration = config
let realm = try Realm()
try realm.write {
realm.deleteAll()
}
return realm.objects(SampleObject.self)
}
+ private var config: Realm.Configuration {
+ Realm.Configuration(schemaVersion: 2) { migration, oldSchemaVersion in
+ if oldSchemaVersion < 2 {
+ migration.enumerateObjects(ofType: SampleObject.className()) { oldObject, newObject in
+ guard let oldObject, let newObject else { return }
+ newObject["primaryKey"] = oldObject["id"]
+ }
+ }
+ }
+ }
}
おわり
オブジェクトを変更してもクラッシュしませんでした!!