How to sort Core Data array based on Date Entered

允我心安 提交于 2021-01-13 09:18:08

问题


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 one property in my model called searchHistory is there a way I can use the following code (key: to sort the data or will I need to add a time saved to the model?

let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        request.sortDescriptors = [NSSortDescriptor.init(key: "", ascending: true)]

回答1:


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.



来源:https://stackoverflow.com/questions/57841461/how-to-sort-core-data-array-based-on-date-entered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!