Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by date - Swift 3

Tags:

I have a func getData() which retrieves core data entity, and I want to sort them by date. How can I apply NSPredicate or Predicate to get the data from CoreData sorted by date?

My core data entity: Entity: Expenses Attributes: - amount - category - date

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

    do {
        expenses = try context.fetch(Expenses.fetchRequest())
    } catch {
        print("Cannot fetch Expenses")
    }
}

Thank you for the help!

like image 363
Kyle Anthony Dizon Avatar asked Feb 27 '17 06:02

Kyle Anthony Dizon


People also ask

How do I sort a string by Date in Swift?

To properly sort it you first need to convert your tSFDATE string to Date and then sort it. let dateFormatter = DateFormatter() dateFormatter. dateFormat = "dd/MM/yyyy - HH:mm:ss" let sortedArray = trackingListArr. sorted { dateFormatter.

How do I sort an array by Date in Swift?

Map your array of history objects to an array of Date objects using a DateFormatter. Use the zip() function to combine the array of history objects and the array of date objects into an array of tuples. Sort the array of tuples. Map the array of tuples back to an array of history objects.

How do I sort Date strings?

To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object.


2 Answers

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.

like image 54
Magnas Avatar answered Dec 25 '22 17:12

Magnas


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
like image 34
Boudhayan Avatar answered Dec 25 '22 18:12

Boudhayan