2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】Realmのオブジェクトを途中で変更する

Last updated at Posted at 2023-05-10

はじめに

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"]
+               }
+           }
+       }
+   }
}

おわり

オブジェクトを変更してもクラッシュしませんでした!!

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?