2012-07-19 3 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

+0

나는 이것이 내가 어떻게 기술했는지를 확신 할 수있다. 그렇게 할 수 있다면 그렇게 해보 라. NSFetchedResultsController는 정렬 프로세스와 관련이 없으며 특히 NSFetchRequest에서 발생합니다 :'fetchRequest.sortDescriptors = sortDescriptors; ' – lawicko

+0

iOS에서 지원되지 않는 것 같습니다 :''NSInvalidArgumentException ', 이유 :'지원되지 않는 NSSortDescriptor 비교기 블록은 지원되지 않습니다). @iawicko는 Mac OS X에서 사용되는 대답입니까? – surlac

관련 문제