按月对数据进行排序

时间:2017-12-11 05:31:02

标签: ios swift sorting

我正在使用

select
    ticketId,
    functionalAreaName as fan,
    ticketTypeName as tan,
    currentTicketStatusName as cts,
    lastUpdatedTimestamp,
    currentTimestamp
from 
    General_Report_Data 
where
    ticketId = "4543218762907648" and
    currentTimestamp in (select max(currentTimestamp) 
                         from General_Report_Data d
                         group by d.ticketId) and 
    (createdTimestamp >= '2017-01-01 00:00:00' and
     createdTimestamp <= CURRENT_TIMESTAMP())

以上代码为我提供了按日期排序的数据。但是我怎样才能按月对数据进行排序。这是我在服务器上的完整日期响应,我在表视图中填充

 self.alldata = self.alldata?.sorted { $0.Edate < $1.Edate }

我怎样才能按月排序?

1 个答案:

答案 0 :(得分:1)

对于这些特定类型的排序,您可能希望将EDate属性拆分为属性组件并使用复合排序描述符(NSSortDescriptor)。排序描述符可能很有用,尤其是当您计划为要对对象排序的键设置优先级时。它允许您引入排序的主要和次要标准,这有时非常有用。

考虑以下示例:

1。从NSObject派生您的对象并将日期分成组件

class MyObject : NSObject {
    @objc dynamic var dateYear : Int
    @objc dynamic var dateMonth : Int
    @objc dynamic var dateDay : Int

    // add Hour or Weekday if needed

    init(dateYear: Int, dateMonth: Int, dateDay: Int) {
        self.dateYear = dateYear
        self.dateMonth = dateMonth
        self.dateDay = dateDay
    }
}

此处,@objc dynamic关键字用于获得与Objective-C&#39;的兼容性。 NSSortComparator,基于KVC。

照常定义数组:

var objects : [MyObject] = [
    MyObject(dateYear: 2017, dateMonth: 12, dateDay: 7),
    MyObject(dateYear: 2017, dateMonth: 11, dateDay: 24),
    MyObject(dateYear: 2016, dateMonth: 5, dateDay: 9),
    MyObject(dateYear: 2016, dateMonth: 2, dateDay: 15),
    MyObject(dateYear: 2014, dateMonth: 7, dateDay: 13),
    MyObject(dateYear: 2016, dateMonth: 11, dateDay: 1)
]

2。制作排序描述符并排序

var descriptor1 = NSSortDescriptor(key: "dateMonth", ascending: true)
var descriptor2 = NSSortDescriptor(key: "dateYear", ascending: true)
var sorted = (objects as NSArray).sortedArray(using: [descriptor1, descriptor2]) as! [MyObject]

输出(月|年|日)

sorted.forEach {
    print($0.dateMonth, $0.dateYear, $0.dateDay)
}

_

2 2016 15
5 2016 9
7 2014 13
11 2016 1
11 2017 24
12 2017 7

指定多个排序描述符可让您确定排序条件的优先级。首先考虑月份,安排提升,然后如果可能的话,按年度安排提升,并保持原样。这是排序描述符有用的地方。

P.S 如果您不需要这些额外的标准而不关心二级订单,那么只需比较两个月的组件:

func month(of date: Date) -> Int {
    return Calendar.current.component(.month, from: date)
}

var sorted = objects.sorted(by: {month(of: $0.Edate) > month(of: $1.Edate) })

PPS 通过使用嵌套NSSortDescriptors循环编写自己的排序算法,可以很好地实现与for相同的功能,但NSSortDescriptor只是方便。