How to sort Core Data array based on Date Entered

前端 未结 1 433
情歌与酒
情歌与酒 2020-12-11 14:15

I have a small Core Data Model which stores an array of Strings (search history).

When fetching the Data I\'d like to sort by the time created. I currently just have

相关标签:
1条回答
  • 2020-12-11 14:43

    Yes, you need a second attribute declared as non-optional Date for example dateCreated. In the NSManagedObject subclass override awakeFromInsert to assign the current date when the record is created.

    override func awakeFromInsert() {
        super.awakeFromInsert()
        dateCreated = Date()
    }
    

    Then you can sort

    request.sortDescriptors = [NSSortDescriptor(key: "dateCreated", ascending: true)]
    

    in ascending order means the oldest entry comes first.

    0 讨论(0)
提交回复
热议问题