我有一個NSFetchedResultsController
,它提供了一個UITableViewController
和Appointment
實體,其中包含一個屬性dateTime
。在NSSortDescriptor中排序(在今天之前或之後)
我的目標是有分類的這樣的任命名單:前天明天
- 今天
- 明天
- 日
- 日
換句話說: 首先sor t在今天之前還是之後,然後是dateTime
。所以首先排序(dateTime > %TODAY%)
,然後在dateTime
本身(未來上升,過去下降)。
有沒有辦法做到這一點?我的問題是,我不能在排序描述符中使用%TODAY%,但也許有另一種方法來實現相同的視覺效果。
UPDATE:請注意接受的答案是不可能的,NSFetchedResultsController
。我選擇了另一個解決方案,在顯示視圖之前訂購Appointments
,將其保存到數據庫,並讓NSFetchedResultsController
選取更改。
UPDATE 2: 接受的答案確實做到了我想要的。我的實現:
let futureAppointments = appointments.filter({ $0.dateTime != nil && $0.dateTime?.compare(Date()) == .orderedDescending })
.sorted(by: { $0.dateTime?.compare($1.dateTime! as Date) == .orderedAscending })
let pastAppointments = appointments.filter({ $0.dateTime != nil && $0.dateTime?.compare(Date()) == .orderedAscending })
.sorted(by: { $0.dateTime?.compare($1.dateTime! as Date) == .orderedDescending })
let sorted = futureAppointments + pastAppointments
for (index, appointment) in sorted.enumerated() {
appointment.order = NSNumber(integerLiteral: index)
}
您不能在fetchRequest中使用基於塊的排序描述符。請參閱https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/PersistentStoreFeatures.html#//apple_ref/doc/uid/TP40001075-CH23-SW1 –
像Jon說的那樣,我無法使用但是這讓我想到了另一種解決方案,在獲取之前使用排序描述符進行排序。現在我有一個屬性'訂單',每次有人打開視圖時都會設置。這從未超過10個左右的約會,所以我沒有看到任何性能問題。謝謝 – Arjan
@Sergey僅供參考您的答案並不完全符合我的要求(我的問題更清楚)。我做了我自己的實現,但如果你願意,歡迎你更新你的答案。 – Arjan