从最后一项获取核心数据ManageObject排序

时间:2018-04-25 10:20:35

标签: swift sorting core-data fetch

我想从Core Data中获取所有项目,但从最新到最旧排序。我的实体“骰子”具有类型为Date的属性“timestamp”。

这是我保存和获取的方式:

class func saveResults(_ withResults: Int) -> Bool {
    let context = getContext()
    let entity = NSEntityDescription.entity(forEntityName: "Dice", in: context)
    let manageObject = NSManagedObject(entity: entity!, insertInto: context)

    let date = Date()

    manageObject.setValue(withResults, forKey: "result")
    manageObject.setValue(date, forKey: "timestamp")

    do {
        try context.save()
        return true
    } catch {
        return false
    }
}

class func fetchObject() -> [Dice]? {
    let context = getContext()
    var dices:[Dice]? = nil

    do {
        dices = try context.fetch(Dice.fetchRequest())
        return dices
    } catch {
        return dices
    }
}

有谁知道如何排序。所有解决方案都令人困惑,并显示从旧到新的分类。

2 个答案:

答案 0 :(得分:1)

您需要指定适当的排序描述符。

我建议创建函数throw并移交错误。

class func fetchObject() throws -> [Dice] {
    let context = getContext()
    let fetchRequest : NSFetchRequest<Dice> = Dice.fetchRequest()
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
    return try context.fetch(fetchRequest)
}

注意:fetch操作返回[Dice]。不需要输入类型。

答案 1 :(得分:0)

你可以这样做

class func fetchObject() -> [Dice]? {
            var dices:[Dice]? = nil
            let context = getContext()
            let fetchDice: NSFetchRequest<Dice> = Dice.fetchRequest()
            let sortDescriptor = [NSSortDescriptor.init(key: "timestamp", ascending: false)]
            fetchDice.sortDescriptors = sortDescriptor
            do
            {
                dices = try context.fetch(fetchDice) 
                return dices
            }catch(let error) {
                print(error.localizedDescription)
                return dices
            }
   }