Swift CoreData sortdescriptions不起作用

时间:2015-03-19 08:23:20

标签: ios swift core-data

我想从coredata获取所有已排序的数据,但它不起作用。 这是我的实体:

class Kurzus: NSManagedObject {

    @NSManaged var kurzuskod: String
    @NSManaged var kurzusnev: String
    @NSManaged var kredit: NSNumber
    @NSManaged var felvett: NSNumber
    @NSManaged var teljesitett: NSNumber
    @NSManaged var jegy: NSNumber
}

这是我的func获取排序数据:

func getSortedData(entity: String, keys: [String], ascend: [Bool]) -> [AnyObject] {
    var request = NSFetchRequest(entityName: entity)
    for i in 0..<keys.count {
        let sd = NSSortDescriptor(key: keys[i], ascending: ascend[i])
        request.sortDescriptors?.append(sd)

    }
    var results = context.executeFetchRequest(request, error: nil)!
    return results
}

但是我收到了未分类的数据...... 我尝试按“kredit”属性对数据进行排序:

println("=========================")
    let res3 = dbHandler.getSortedData(entity, keys: ["kredit"], ascend: [true]) as [Kurzus]
    for k in res3 {
        println("Kurzuskód: \(k.kurzuskod) \nKurzusnev: \(k.kurzusnev)\nKredit: \(k.kredit)\nFelvett: \(k.felvett)\nTeljesitett: \(k.teljesitett)\nJegy: \(k.jegy)")
}

但它没有排序,这有什么不对吗?

1 个答案:

答案 0 :(得分:1)

默认情况下,request.sortDescriptorsnil,因此可选 链

request.sortDescriptors?.append(sd)

什么都不做。您必须先创建一个数组然后再创建一个数组 附加排序描述符:

let request = NSFetchRequest(entityName: entity)
request.sortDescriptors = [] // <-- Start with empty array!
for i in 0..<keys.count {
    let sd = NSSortDescriptor(key: keys[i], ascending: ascend[i])
    request.sortDescriptors!.append(sd)
}

使用map()

,这也可以更加流畅
let request = NSFetchRequest(entityName: entity)
request.sortDescriptors = map(0 ..< keys.count) {
    NSSortDescriptor(key: keys[$0], ascending: ascend[$0])
}

map() + Zip2(创建一系列对 来自给定的数组):

let request = NSFetchRequest(entityName: entity)
request.sortDescriptors = map(Zip2(keys, ascend)) {
    NSSortDescriptor(key: $0, ascending: $1)
}