问题描述
我有一个小的核心数据模型,该模型存储一个字符串数组(搜索历史记录).
I have a small Core Data Model which stores an array of Strings (search history).
在获取数据时,我想按创建时间进行排序.我目前在模型中只有一个名为searchHistory
的属性,是否可以使用以下代码(key:
对数据进行排序,还是需要向模型添加保存的时间?
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)]
推荐答案
是的,您需要一个声明为非可选Date
的第二个属性,例如dateCreated
.在NSManagedObject
子类中,覆盖awakeFromInsert
以分配创建记录时的当前日期.
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()
}
然后您可以排序
request.sortDescriptors = [NSSortDescriptor(key: "dateCreated", ascending: true)]
按ascending
顺序表示最早的条目排在最前面.
in ascending
order means the oldest entry comes first.
这篇关于如何根据输入的日期对核心数据数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!