我想从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
}
}
有谁知道如何排序。所有解决方案都令人困惑,并显示从旧到新的分类。
答案 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
}
}