Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

ios - How to sort Core Data array based on Date Entered

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)]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...