2015-12-15 90 views
11

我不知道如何使用Realm進行排序。我目前的代碼是。如何使用領域進行排序?

data = realm.objects(WorkoutSet) 
data = data!.sorted("date") 

我想的Int從高數量低的數字排序日期。該文檔需要更多信息,並且GitHub鏈接會拋出一條404消息。

+0

你能解釋一下'sort date和Int from 1 to 0'是什麼意思嗎? – joern

+0

我剛編輯它。 –

+0

'data!'中的感嘆號('!')做了什麼? –

回答

28

您可以在ascending參數添加到sorted方法:

data = data!.sorted("date", ascending: false) 

使用按照從大到小的順序日期字段排序這個你WorkoutSet。

更新

與SWIFT 3和最新的RealmSwift版本現在已更改爲:

data = data!.sorted(byKeyPath: "date", ascending: false) 

如果你想自己評估排序標準,你可以使用:

data = data!.sorted(by: { (lhsData, rhsData) -> Bool in 
    return lshData.something > rhsData.something 
}) 

但請注意,自行排序結果確實會返回Array而不是Realm Results對象。這意味着會有性能和內存開銷,因爲Results是懶惰的,如果使用上述方法進行排序,您將失去這種懶惰行爲,因爲Realm必須評估每個對象!只要可能,你應該堅持結果。如果確實沒有其他方法來分揀物品,請僅使用上述方法。

+0

我認爲我們需要在{}中包含升序:false,按排序(「date」,{rise:false}) – NgocDB

+0

不,這是不正確的。 'ascending'是一個簡單的布爾參數。請參閱上面我更新的答案。 – joern

+0

啊,是的,它是與斯威夫特,你澄清。使用Realm Javascript時,我們需要按照我所說的排序(「date」,{rise:false})來使用 – NgocDB

0

使用Sort.ASCENDING或Sort.DESCENDING

import java.util.Date; 

import io.realm.RealmModel; 
import io.realm.annotations.Index; 
import io.realm.annotations.PrimaryKey; 
import io.realm.annotations.RealmClass; 
import io.realm.annotations.Required; 

@RealmClass 
public class Pojo implements RealmModel { 
    @Index 
    @Required 
    @PrimaryKey 
    protected Long id; 
    protected Date data_field; 
    protected int int_field; 

    public Long getId() { 
     return id; 
    } 

    public void setId(Long id) { 
     this.id = id; 
    } 
} 

import java.util.List; 

import io.realm.Realm; 
import io.realm.RealmQuery; 
import io.realm.RealmResults; 
import io.realm.Sort; 

public class Dao { 
    public List<Pojo> getAllById(Long id) { 
     Realm realm = Realm.getDefaultInstance(); 
     RealmQuery<Pojo> query = realm.where(Pojo.class); 
     query.equalTo("pojo_id", id); 

     RealmResults<Pojo> result = query.findAll(); 

     result = result.sort("data_field", Sort.ASCENDING); 
     result = result.sort("int_field", Sort.DESCENDING); 

     //detaching it from realm (optional) 
     List<Pojo> copied = realm.copyFromRealm(result); 

     realm.close(); 

     return copied; 
    } 
} 
0

realmResults.sort( 「日期」,TRUE);