2017-03-06 33 views
1

我有一個NSFetchedResultsController,它提供了一個UITableViewControllerAppointment實體,其中包含一個屬性dateTime在NSSortDescriptor中排序(在今天之前或之後)

我的目標是有分類的這樣的任命名單:前天明天

  • 後,昨天

    1. 今天
    2. 明天

    換句話說: 首先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) 
    } 
    
  • 回答

    0

    這是唯一的想法。可能是你可以創建sortdescriptor這樣的:

    NSSortDescriptor(key: "test", ascending: true) { (v1, v2) -> ComparisonResult in 
         guard let d1 = v1 as? Date else 
         { 
          return .orderedAscending 
         } 
         guard let d2 = v2 as? Date else 
         { 
         return .orderedAscending 
         } 
         if abs(d1.timeIntervalSinceNow) < abs(d2.timeIntervalSinceNow) { return .orderedAscending } 
         if abs(d1.timeIntervalSinceNow) > abs(d2.timeIntervalSinceNow) { return .orderedDescending } 
         return .orderedSame 
    } 
    

    我認爲這將是工作。

    +0

    您不能在fetchRequest中使用基於塊的排序描述符。請參閱https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/PersistentStoreFeatures.html#//apple_ref/doc/uid/TP40001075-CH23-SW1 –

    +0

    像Jon說的那樣,我無法使用但是這讓我想到了另一種解決方案,在獲取之前使用排序描述符進行排序。現在我有一個屬性'訂單',每次有人打開視圖時都會設置。這從未超過10個左右的約會,所以我沒有看到任何性能問題。謝謝 – Arjan

    +0

    @Sergey僅供參考您的答案並不完全符合我的要求(我的問題更清楚)。我做了我自己的實現,但如果你願意,歡迎你更新你的答案。 – Arjan

    1

    使用兩個fetchedResultsControllers,一個分類與排除今天之前創建的那些謂詞上升,和一個分類與排除未來的約會謂詞下降。

    編寫一個函數來在fetchedResultsController indexPath和tableview的indexPath之間進行轉換,反之亦然。只要確保跟蹤你正在處理的是哪種indexPath,這並不難。

    +0

    嗨,喬恩,我實際上有一個基類'CoreDataTableViewController',我不想改變或複製一個屏幕,所以我去了另一種解決方案。謝謝你的想法。 – Arjan

    相關問題