Sort by date - Swift 3

You need a sort descriptor to get all the objects in a specific order.

let sectionSortDescriptor = NSSortDescriptor(key: "date", ascending: true)
let sortDescriptors = [sectionSortDescriptor]
fetchRequest.sortDescriptors = sortDescriptors

Predicates are for filtering your search results. To sort them you need to use an NSSortDescriptor. Assuming you have an attribute on your Expenses entity called date of type Date:

func getData() {
    let context = appDelegate.persistentContainer.viewContext  

    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")
    }
}

EDIT: I should have mentioned that the sort selector is added in an array so that multiple sort descriptors can be added if needed. e.g. sort first by date, then by number of legs, then by volume, etc.


My function to do a fetchRequest of data in Core Data and sort the results by date "timestamp" in descending order. "Ruta" is the name of the entity.

//Array of Ruta entity
    rutas = [Ruta]()

    func getData() {

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Ruta")
        let sort = NSSortDescriptor(key: "timestamp", ascending: false)
        request.sortDescriptors = [sort]

        do {
            rutas = try context.fetch(request) as! [Ruta]
        } catch {
            print("Fetching Failed")
        }
    }