Swift按日期排序核心数据(不仅仅是时间)

时间:2017-02-06 03:55:53

标签: swift core-data swift3 nssortdescriptor

我正在使用核心数据在Swift中构建应用。我正在使用具有Date属性的任务实体。我需要根据截止日期对任务进行排序。

我尝试使用带有密钥到期的NSSortDescriptor

Please enter your guess, number must be between 0 and 1000: 256
Getting warm but still too low!
Too Low!
Please enter your guess, number must be between 0 and 1000: 257
Great Guess! The number was 257 and you guessed it in 13 tries!

问题:

它仅按时间对我的数据进行排序 - 不考虑日/月/年

这是我从获取请求中获得的数据:

NSSortDescriptor.init(key: "due", ascending: false)

我怎样才能通过更快的方式对其进行排序? (考虑整个NSDate而不仅仅是时间部分)

我希望它是:

Optional(2017-02-06 03:29:18 +0000)
Optional(2017-02-08 03:29:27 +0000)
Optional(2017-02-07 03:29:38 +0000)
Optional(2017-02-08 03:30:29 +0000)

完整代码     完成的所有任务在列表中都是0,我正在呼叫:

Optional(2017-02-06 03:29:18 +0000)
Optional(2017-02-07 03:29:38 +0000)
Optional(2017-02-08 03:29:27 +0000)
Optional(2017-02-08 03:30:29 +0000)

helper func:

helper(showComp: true, sortBy: NSSortDescriptor.init(key: "due", ascending: false))

核心数据属性的照片 enter image description here

1 个答案:

答案 0 :(得分:1)

Swift 3

var sdSortDate = NSSortDescriptor.init(key: "date", ascending: false)
fr.sortDescriptors = [sdSortDate]
let result4 = try! context.fetch(fr)

我在Swift 3中测试过,效果很好

[<NSManagedObject: 0x618000089060> (entity: CoreDate; id: 0x61800002c460 <x-coredata://E7D9FD6F-5DCF-464B-93BF-D1609BF35695/CoreDate/p3> ; data: {
    date = "2017-02-09 21:35:19 +0000";
}), <NSManagedObject: 0x61800008b680> (entity: CoreDate; id: 0x60000002c140 <x-coredata://E7D9FD6F-5DCF-464B-93BF-D1609BF35695/CoreDate/p1> ; data: {
    date = "2017-02-06 04:41:59 +0000";
}), <NSManagedObject: 0x60800008c080> (entity: CoreDate; id: 0x60800002d460 <x-coredata://E7D9FD6F-5DCF-464B-93BF-D1609BF35695/CoreDate/p2> ; data: {
    date = "2017-02-17 18:28:39 +0000";
})]

After sort

[<NSManagedObject: 0x61800008b680> (entity: CoreDate; id: 0x60000002c140 <x-coredata://E7D9FD6F-5DCF-464B-93BF-D1609BF35695/CoreDate/p1> ; data: {
    date = "2017-02-06 04:41:59 +0000";
}), <NSManagedObject: 0x618000089060> (entity: CoreDate; id: 0x61800002c460 <x-coredata://E7D9FD6F-5DCF-464B-93BF-D1609BF35695/CoreDate/p3> ; data: {
    date = "2017-02-09 21:35:19 +0000";
}), <NSManagedObject: 0x60800008c080> (entity: CoreDate; id: 0x60800002d460 <x-coredata://E7D9FD6F-5DCF-464B-93BF-D1609BF35695/CoreDate/p2> ; data: {
    date = "2017-02-17 18:28:39 +0000";
})]