2012-07-19 38 views
2

我成功地使用一個NSFetchedResultsController和一個NSSortDescriptor分類到一個表中,每個日期都有一個部分,所以今天的日期首先出現(降序日期順序)。如何按日期降序對NSDate進行排序,但隨着時間的推移在該日期內上升?

但是,在該部分中,我希望按升序對時間進行排序。

這是我沒有按時間排序當前代碼:

//Set up the fetched results controller. 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:kEntityHistory inManagedObjectContext:global.managedObjectContext]; 
fetchRequest.entity = entity; 

// Sort using the timeStamp property.. 
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO]; 
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; 

fetchRequest.sortDescriptors = sortDescriptors; 

//The following is from: 
//http://stackoverflow.com/questions/7047943/efficient-way-to-update-table-section-headers-using-core-data-entities 

NSString *sortPath = @"date.dayDate"; 

self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:global.managedObjectContext sectionNameKeyPath:sortPath cacheName:nil]; 

fetchedResultsController.delegate = self; 

它是如何將有可能改變代碼來添加這個日期段內按時間排序上升嗎?

回答

3

我想你需要一個特殊的比較器。使用initWithKey:ascending:comparator:初始化您的排序描述符和作爲比較通過這個:

^(id obj1, id obj2) { 
    NSDateComponents *components1 = [[NSCalendar currentCalendar] components:NSHourCalendarUnit|NSDayCalendarUnit fromDate:obj1]; 
    NSInteger day1 = [components1 day]; 
    NSInteger hour1 = [components1 hour]; 

    NSDateComponents *components2 = [[NSCalendar currentCalendar] components:NSHourCalendarUnit|NSDayCalendarUnit fromDate:obj2]; 
    NSInteger day2 = [components2 day]; 
    NSInteger hour2 = [components2 hour]; 

    NSComparisonResult res; 
    if (day1>day2) { 
     res = NSOrderedAscending; 
    } else if (day1<day2) { 
     res = NSOrderedDescending; 
    } else { 
     if (hour1>hour2) { 
      res = NSOrderedDescending; 
     } else { 
      res = NSOrderedAscending; 
     } 
    } 
    return res; 
} 

這應該給你的想法如何可以做到這一點,你將需要添加分秒組件,並且還處理情況小時,分鐘和秒鐘相等。

+0

謝謝 - 有道理。我已經發現(我認爲)NSFetchedResultsController不支持自定義排序描述符,所以明天我將嘗試在獲取的數組上使用您的代碼,然後解決如何將它放回到部分。 – Caroline 2012-07-19 13:21:14

+0

我很確定這應該如何描述它,所以如果可以的話,先試試。 NSFetchedResultsController與排序過程沒有太大關係,這一切都發生在NSFetchRequest中,具體如下:'fetchRequest.sortDescriptors = sortDescriptors;' – lawicko 2012-07-19 13:37:22

+0

看起來它不支持iOS:''NSInvalidArgumentException',原因:'不支持NSSortDescriptor比較器塊不支持)''。 @iawicko是你應該在Mac OS X上使用的答案嗎? – surlac 2013-02-04 08:56:16

相關問題