如何根据输入的日期对核心数据数组进行排序 [英] How to sort Core Data array based on Date Entered

查看:101
本文介绍了如何根据输入的日期对核心数据数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的核心数据模型,该模型存储一个字符串数组(搜索历史记录).

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.

这篇关于如何根据输入的日期对核心数据数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆