1

Think of the Alarm app on the iPhone, the alarms are sorted by time. Say these alarms were stored in Core Data with the date component being the actual date they were created, but with the time component chosen by a date picker. So when fetching these, you need to ignore the date component and sort them by time only.

This works if all the alarms are created on the same date:

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

But if they're created on separate days, obviously the ones created first are listed first by date, and sorted by time within each date group. I want to completely ignore the date component when doing this sort and order everything by the time component only.

tariq
  • 501
  • 2
  • 4
  • 11

1 Answers1

2
  • Create a global date formatter in the NSManagedObject subclass

    let timeFormatter : DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "HH:mm:ss"
        return formatter
    }()
    
  • and a computed property

    @objc var time : String {
        return timeFormatter.string(from: date)
    }
    
  • Then fetch the records unsorted and sort them manually

    let sortedRecords = records.sorted{ $0.time < $1.time }
    
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Great idea! I think I'm missing something though: `Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath time not found in entity '` Do I need to add "time" in the model editor as well? – tariq Jan 05 '20 at 18:58
  • thanks. I'm using NSFetchedResultsController though, which doesn't seem to give the opportunity to sort records like that. How would I modify for that? – tariq Jan 05 '20 at 21:48