RealmList in RealmObject. How to persist order?

时间:2016-10-09 15:51:02

标签: android realm realm-list

I have a RealmObject with a RealmList as one of its field.

public class ToyMaker extends RealmObject {
    private RealmList<Toy> toyList;
    ...
}

public class Toy extends RealmObject {
    ...
}
  1. Will the ordering of Toy in toyList be persisted when written to Realm and reading it back?

  2. If ordering is not persisted by Realm, how can i achieve this manually given that

    A. I cannot add additional fields (e.g. index) in Toy class (a Toy can have many ToyMaker so an index field in Toy is not feasible.

    B. The ordering is in the order that Toy is added to toyList.

1 个答案:

答案 0 :(得分:6)

订购了RealmList,因此案例#1是正确的。只需按照您想要的顺序添加它们,该订单将被保留。

一般情况下,订购并不能保证,因此在Realm中创建2个对象并不意味着订单:

realm.createObject(Person.class, 1);
realm.createObject(Person.class, 2);

// Doing this is not guaranteed to return Person:1
realm.where(Person.class).findAll().first()

// Always use a sort in queries if you want a specific order
realm.where(Person.class).findAllSorted("id", Sort.ASCENDING).first();