按日期排序-Swift 3 [英] Sort by date - Swift 3

查看:283
本文介绍了按日期排序-Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个func getData()来检索核心数据实体,我想按日期对它们进行排序。如何应用NSPredicate或Predicate从CoreData中获取按日期排序的数据?

I have a func getData() which retrieves core data entity, and I want to sort them by date. How can I apply NSPredicate or Predicate to get the data from CoreData sorted by date?

我的核心数据实体:
实体:费用
属性:
-金额
-类别
-日期

My core data entity: Entity: Expenses Attributes: - amount - category - date

func getData() {
    let context = appDelegate.persistentContainer.viewContext

    do {
        expenses = try context.fetch(Expenses.fetchRequest())
    } catch {
        print("Cannot fetch Expenses")
    }
}

感谢您的帮助!

推荐答案

谓词用于过滤搜索结果。要对它们进行排序,您需要使用NSSortDescriptor。假设您在Expenses实体上有一个称为Date类型的日期的属性:

Predicates are for filtering your search results. To sort them you need to use an NSSortDescriptor. Assuming you have an attribute on your Expenses entity called date of type Date:

func getData() {
    let context = appDelegate.persistentContainer.viewContext  

    let fetchRequest = NSFetchRequest<Expenses>(entityName: "Expenses")
    let sort = NSSortDescriptor(key: #keyPath(Expenses.date), ascending: true)
    fetchRequest.sortDescriptors = [sort]
    do {
       expenses = try context.fetch(fetchRequest)
    } catch {
        print("Cannot fetch Expenses")
    }
}

编辑:我应该提到排序选择器是添加到数组中,以便在需要时可以添加多个排序描述符。例如首先按日期排序,然后按腿数排序,然后按音量排序,等等。

I should have mentioned that the sort selector is added in an array so that multiple sort descriptors can be added if needed. e.g. sort first by date, then by number of legs, then by volume, etc.

这篇关于按日期排序-Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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