Search code examples
iosswiftrealmrealm-mobile-platform

Swift - How to update objects in bulk with out iterating over a collection of realm objects


I have nearly a hundred thousand records in my realmDB and I want to re-calculate a particular property every time the user changes his device timezone based on the other property in the same table.

Example :

    class Activity: Object {
        // In UTC received from server
         dynamic var effectiveDate: Date? 
        // Needs to be re-calculated everytime user launches the app based on `effectiveDate`
         dynamic var effectiveDay: Date? 
   }

Assumption: I have 100,000 such activity records in my realm table called Activities

Also, realm states that applying KVC to a collection is a great way to update objects in bulk without the overhead of iterating over a collection while creating accessors for every item.

In my case instead of setting the same value for every record, I want to re-calculate the effectiveDay based on effectiveDate property for every record using KVC to avoid the overhead of iterations. Is it possible?


Solution

  • Short answer:

    It is not possible without iterating over a collection of realm objects.

    Long answer:

    The realm is a model class based database. It does not support any query (Predicates or Filter mostly used to retrieve data with a specific condition) like SQLite means We can't update all record in a single query by using the realm. So answer of your question is pretty straightforward, Without iterating we can not update the value.

    You can improve performance if you want to change the value of some object.

    Code:

    let persons = realm.objects(Person.self).filter("id IN %@", ids)
    try! realm.write {
        persons.first?.setValue(true, forKeyPath: "isFirst")
        // set each person's planet property to "Earth"
        persons.setValue("Earth", forKeyPath: "planet")
    }