如何按Date排序对象数组

时间:2017-12-21 15:31:47

标签: arrays swift

我有一个名为费用的核心数据项,它具有不同的属性,例如

expense.name
expense.amount

以及

expense.modificationDate

我有一个类型为费用的数组,我想对数组进行排序。 到目前为止我试过这个

  monthlyExpenses.sort(by: { $0.modificationDate?.compare($1.modificationDate! as Date) == .orderedAscending })

但它似乎不起作用。我怎样才能让它发挥作用?

3 个答案:

答案 0 :(得分:2)

monthlyExpense.sorted({ $0.modificationDate> $1.modificationDate})

它将按升序和降序排序<。

答案 1 :(得分:1)

  let fetchRequest = NSFetchRequest<Expenses>(entityName: "Expenses")
let sort = NSSortDescriptor(key: #keyPath(Expenses.date), ascending: true)
fetchRequest.sortDescriptors = [sort]
do {
   expenses = try context.fetch(fetchRequest)
} catch {
    print("Cannot fetch Expenses")
}

Answer was here

答案 2 :(得分:0)

在您的抓取过程中使用NSSortDescriptors。例如:

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "expense")
let sortDescriptor = NSSortDescriptor(key: "modificationDate", ascending: true)


  fetchRequest.sortDescriptors = [sortDescriptor]

  return fetchRequest