solidcell solidcell - 2 months ago 7
Swift Question

Sorting Realm records that are inserted quickly

Sometimes my app will add many Realm records at once.
I need to be able to consistently keep them in the same order.

The documentation recommends that I use

:


Another common motivation for auto-incrementing properties is to preserve order of insertion. In some situations, this can be accomplished by appending objects to a List or by using a createdAt property with a default value of NSDate().


However, since records are added so quickly sometimes, the dates are not always unique, especially considering Realm stores
NSDate
only to the second accuracy.

Is there something I'm missing about the suggestion in the documentation?

Maybe the documentation wasn't considering records added in quick succession?
If so, would it be recommended to keep an
Int
position
property and to always query for the last record at the moment when adding a new record, so as to ensure sequential positions?

However, querying for the last record in such a case won't return the previous record unless you've also added and finalized a write, which is wasteful if you need to add a lot of records.

Then, it would require batch create logic, which is unfortunate.

Answer

However, since records are added so quickly sometimes, the dates are not always unique, especially considering Realm stores NSDate only to the second accuracy.

The limitation on date precision was addressed back in Realm v0.101. Realm can now represent dates with greater precision than NSDate.

However, querying for the last record in such a case won't return the previous record unless you've also added and finalized a write, which is wasteful if you need to add a lot of records.

It's not necessary to commit a write transaction for queries on the same thread to see data that you've added during the write transaction.

Is there something I'm missing about the suggestion in the documentation?

You skipped over the first suggestion: appending objects to a List. Lists in Realm are inherently ordered, so you do not need to find a way to create unique, ordered values. Simply append the new object to the list, and rely on the list's order to determine the order in which the objects were added. This also has the advantage of being safe when using Realm Mobile Platform's synchronization features, as incrementing fields can generate duplicates on different devices and timestamps may not be reliable.

Comments