1

我有一个带有 NSSortDesctriptors 的 NSFetchRequest 附加到 NSFetchedResultController 为处于分组模式并显示部分标题的 UITableView 提供数据(参见表示例)。

我在正确排序以显示部分时遇到了一些问题。

数据:

+---+----------+------------+----------+
|id | subTitle | groupTitle | distance |
+---+----------+------------+----------+
|1  | A        | T1         | 1.1      |
+---+----------+------------+----------+
|2  | B        | T1         | 1.2      |
+---+----------+------------+----------+
|3  | C        | T1         | 3.0      |
+---+----------+------------+----------+
|4  | D        | T2         | 1.3      |
+---+----------+------------+----------+
|5  | E        | T2         | 1.4      |
+---+----------+------------+----------+
|6  | F        | T3         | 1.5      |
+---+----------+------------+----------+

我有的:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"groupTitle" ascending:YES];

--T1
------A
------B
------C
--T2
------D
------E
--T3
------F

我想要什么:(按距离排序,但对同一组中的以下每个项目按 groupTitle 分组)

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES];

--T1
------A
------B
--T2
------D
------E
--T3
------F
--T1
------C

我怎样才能实现这种行为?可能使用 viewForHeaderInSection 方法?如果要分组的部分不在第一个层次结构中[self.fetchedResultsController sections]怎么办?

//custom header
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    id<NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    SomeObject *cellEntity = (SomeObject *)[[sectionInfo objects] objectAtIndex:0];
    //cellEntity.groupTitle is the title 
    return aView;
}
4

1 回答 1

0

您是否尝试过以这种方式设置您的 NSFetchedResultsController?这应该首先按组标题排序,然后按距离排序。然后它应该由小组打破它。

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
NSSortDescriptor *groupTitleSort = [NSSortDescriptor sortDescriptorWithKey:@"groupTitle" ascending:YES];
NSSortDescriptor *distanceSort = [NSSortDescriptor sortDescriptorWithKey:distance ascending:YES];
NSArray *sortArray = [NSArray arrayWithObjects:groupTitleSort, distanceSort, nil];
request.sortDescriptor = sortArray;
NSFetchedResultController *fetchedResults = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:myManagedObjectContext sectionNameKeyPath:@"groupTitle" cacheName:@"MyCache"];

...Finish performing fetch...
于 2012-04-26T14:00:08.357 回答