0

I have a Core Data item called an expense, which has different properties such as

expense.name
expense.amount

and also

expense.modificationDate

I have an array, which is of type expenses, and I want to sort the array. I have tried this so far

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

but it doesn't seem to work. How can I get this to work?

2
  • Why not sorting the data before the fetch? It has better optimization. Commented Dec 21, 2017 at 15:40
  • 3
    Define "doesn't work". Commented Dec 21, 2017 at 15:43

3 Answers 3

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

It will sort by ascending and for descending use <.

Sign up to request clarification or add additional context in comments.

3 Comments

just make sure to include a space between modificationDate and the operator >.
Tells me that i cant use a binary operator on 2 NSDate operands
@A.G I think you should use Date() not NSDate
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

Comments

0

Use NSSortDescriptors during your fetch. as Example:

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


  fetchRequest.sortDescriptors = [sortDescriptor]

  return fetchRequest

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.