1

I have a List of objects, which I need to sort by a date property. I'm using that list to display the items in a UITableView

My problem is that, sorting a List in Realm returns a Results<myItem> instead of a List<myItem> object.

What is the proper way to sort a List in Realm without converting it into a Results object?

Aks4125
  • 4,522
  • 4
  • 32
  • 48
amirfl
  • 1,634
  • 2
  • 18
  • 34
  • What is the reason you require it to be a list? – Gori Jan 02 '19 at 22:47
  • The List has a to-many relationship to a parent object, so it is natural to leave it as a list – amirfl Jan 02 '19 at 22:56
  • Ah I see. In that case, it would seem most logical to me to insert the objects in a sorted manner, instead of sorting them later on. – Gori Jan 02 '19 at 23:01
  • Thing is that the date can be later changed by the user, requiring a sort again – amirfl Jan 02 '19 at 23:02
  • Well, in that case you could of course check what position the object should move to, and use the `move(from:to:)` function to change the order. I don't know how efficient this would be though. – Gori Jan 02 '19 at 23:04
  • 1
    Otherwise, I think using the built-in `sorted` function would be the way to go, especially since it would update automatically, even though you would prefer to not use that – Gori Jan 02 '19 at 23:09
  • @Gori sorting the list into a Results object is the workaround I ended up using. Unfortunately, it doesn’t persist the List in the correct order, but at least it lets me display it correctly. – amirfl Jan 07 '19 at 17:23

1 Answers1

0

Workaround can be:

  1. add extra field like timestamp of your date property (in millis), everytime you insert a record. (not required if you are sorting data based on data field)
  2. sort query data = data!.sorted(byKeyPath: "date", ascending: false) for more options
  3. Realm query will return RLMResult only.for unmanaged object
Aks4125
  • 4,522
  • 4
  • 32
  • 48