LoginSignup
5
7

More than 5 years have passed since last update.

RealmのResultsは常に最新の状態を保っている

Posted at

RealmのResultsはNSFastEnumerationを実装しているため、ついついArrayのように使いがちですが、Realmの基本Object同様データの更新が逐一反映される点には注意が必要です。

例えば以下の例が分かりやすいです。

        let realm = try! Realm()

        let hellos = realm.objects(Sample).filter("title = 'hello'")

        print(hellos.count)

        try! realm.write { () -> Void in
            let sample = Sample()
            sample.title = "hello"
            realm.add(sample)
        }

        print(hellos.count)

2つのprint文がありますが、この2つは違う値を表示します。
hellosインスタンスは同じでも、realm.addが完了した時点でhellosの要素数が1増える為です。

分かりにくい例としては、このrealm.addが別の場所で行われていたり、複雑なクエリを書いてその結果を持っている時です。
特に複雑なクエリを書いていると、結果が出てきてその結果が静的であると思い込みですが、そのクエリに適合する内容に逐一更新されるため注意が必要です。

逆にResultsからArrayにする場合は

array = hellos.map({$0})

という書き方が便利です。

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