netshark1000
netshark1000

Reputation: 7403

Realm slow on updating multiple objects

In my app the user can select multiple contacts in a collectionview. when he selects the property "isSelected" will me set to true and the collectionview refreshes the selected cell. Here I can recognize a small delay between selection and the highlighting of the cell. But in the next step I create a group with the selected contacts and in the end I set the property "isSelected" to false. This takes an non acceptable amount of time for 50 objects (5 seconds) and needs to be tuned.

Here is my code to unselect all the selected contacts:

for contact in self.selectedContacts {
            try! self.realm.write{
                contact.isSelected = false;
                self.realm.add(contact, update: true)
            }
        }

Is it possible to perform a batch-update at once?

Upvotes: 8

Views: 4885

Answers (2)

Piyush
Piyush

Reputation: 1224

You should add Toggle selection logic out side of write block. for speed up Realm updating process.

    for contact in self.selectedContacts {
        contact.isSelected = false;
    }
    try! self.realm.write{
        self.realm.add(self.selectedContacts, update: true)
    }

Upvotes: 0

joern
joern

Reputation: 27620

Try putting the for loop inside the write block:

try! self.realm.write {
    for contact in self.selectedContacts {
        contact.isSelected = false;
        self.realm.add(contact, update: true)
    }
}

Upvotes: 20

Related Questions