Search code examples
iosswiftcore-datansfetchrequestnssortdescriptor

Swift CoreDate Fetch by Date and Time Stored as String and Sort


In CoreDate Table, I am storing Date and Time as String in below format and I have a specific reason for storing as a string.

static let DateFmtVal = "dd-MM-yyyy";
static let TimeFmtVal = "hh:mm a";

Now while fetching I want to sort by converting the string to Date and Time and sort to display in TableView, so the row with newer ones come on top

let DateSortVar = NSSortDescriptor(key: DateCol, ascending: false)
let TimeSortVar = NSSortDescriptor(key: TimeCol, ascending: false)
fetchedResultsController.fetchRequest.sortDescriptors = [DateSortVar, TimeSortVar]

In Android, Using SQLite I got the solution as :

SqlQryVar = "SELECT * FROM " + NamTblVal +
                        " ORDER BY STRFTIME('%d-%m-%Y %h:%i'," + DateCol + "|| ' ' ||" + TimeCol + ") DESC;";

So kindly help me to do the same in Swift


Solution

  • You can add a computed property of type Date to your CoreData object (In your subclass ), do your conversions there and pass only it to the sort descriptor and you will get the same behavior like in your Android app, BUT take into consideration that what is different in iOS from Android that converting String to Date in iOS is slow!!! And allocating several DateFormatters is expensive (But you can use one for all your conversions). So if you don't have a lot of dates then it could work for you , anyway if you want to get the right sorted data then you will have to convert at some point. Another solution without converting to date is considering to use other format for the date column i.e "yyyy-mm-dd" then the String sort will match the date.