Search code examples
iosrealmsequences

strange record order of Realm


I'm using realm db(https://realm.io/) in iOS app, I found a strange behavior. I insert several records to a table in the order record1, record2 and record3, however, in one of my customer's iPad, the order of read result is random, but in my iPad, the read order is always the same as insert:record1, record2 and record3.

Does anyone has some clues why that happen?


Solution

  • By default, the ordering of Realm objects when inserted into a database isn't guaranteed.

    If you want to explicitly control the ordering of a list of objects, best practice is to create another Realm model class (eg MyObjectList), add a Realm List object to it, and add the objects you wish to order as children of that object.

    Another way is to add an extra property to your objects, like orderedIndex and have that incrementing upwards. When you query for your objects, you then use the .sort() method to sort by that property.