领域 findAllSorted by field of a filed
Realm findAllSorted by field of a filed
另一个关于领域的问题。
我有这个结构;
Class A 有一个 class B,它有一个字符串名称。
我想按名称为 "xy";
的 B b 对 Class A 的列表进行排序
所以这是我尝试过但不起作用的方法。
realm.where(A.class).findAllSorted("b.name",true);
这表示没有字段B.name。
有什么想法可以让它发挥作用吗?
谢谢。
Realm 尚不支持按 link 排序。有一个 open issue 跟踪这个 .
这是 Realm 支持该功能之前的解决方法:
class A extends RealmObject {
private B b;
// Storing the b.name as a field of A when calling setB(). But
// remember you cannot do it by adding logic to setB() since Realm's
// proxy will override the setters. You can add a static method to
// achieve that.
private String bName;
// getters and setters
// This needs to be called in a transaction.
public static void setBObj(A a, B b) {
a.setB(b);
a.setBName(b.getName);
}
}
然后您可以按 bName 对结果进行排序,例如:
realm.where(A.class).findAllSorted("bName",true);
我同意@beeender,你也可以使用 wrapper 以 java 风格来完成它:
1.Define A.class 和
的包装器
public class AWrapper {
public AWrapper(A a){
this.a = a;
}
private A a;
}
2。转换包装器中的所有 RealmObject。像这样思考:
List<AWrapper> wrapped = new ArrayList<>();
for(A a : realmSet){
wrapped.add(new AWrapper(a))
}
实现你自己的比较器来比较来自 A.class
的一些字段
private class OwnComparator implements Comparator<AWrapper>{
@Override
int compare(AWrapper o1, AWrapper o2) {
return o1.someField.compareTo(o2.someField)
}
}
使用 utils.Collections 排序 class
Collections.sort(wrapped, new OwnComparator())
另一个关于领域的问题。
我有这个结构;
Class A 有一个 class B,它有一个字符串名称。
我想按名称为 "xy";
的 B b 对 Class A 的列表进行排序所以这是我尝试过但不起作用的方法。
realm.where(A.class).findAllSorted("b.name",true);
这表示没有字段B.name。
有什么想法可以让它发挥作用吗?
谢谢。
Realm 尚不支持按 link 排序。有一个 open issue 跟踪这个 .
这是 Realm 支持该功能之前的解决方法:
class A extends RealmObject {
private B b;
// Storing the b.name as a field of A when calling setB(). But
// remember you cannot do it by adding logic to setB() since Realm's
// proxy will override the setters. You can add a static method to
// achieve that.
private String bName;
// getters and setters
// This needs to be called in a transaction.
public static void setBObj(A a, B b) {
a.setB(b);
a.setBName(b.getName);
}
}
然后您可以按 bName 对结果进行排序,例如:
realm.where(A.class).findAllSorted("bName",true);
我同意@beeender,你也可以使用 wrapper 以 java 风格来完成它:
1.Define A.class 和
的包装器public class AWrapper {
public AWrapper(A a){
this.a = a;
}
private A a;
}
2。转换包装器中的所有 RealmObject。像这样思考:
List<AWrapper> wrapped = new ArrayList<>();
for(A a : realmSet){
wrapped.add(new AWrapper(a))
}
实现你自己的比较器来比较来自 A.class
的一些字段private class OwnComparator implements Comparator<AWrapper>{ @Override int compare(AWrapper o1, AWrapper o2) { return o1.someField.compareTo(o2.someField) } }
使用 utils.Collections 排序 class
Collections.sort(wrapped, new OwnComparator())