使用获取的结果控制器进行排序会导致节标题错误

时间:2010-12-24 17:27:33

标签: iphone cocoa-touch uitableview

我正在使用fetchedResultsController来获取表视图的数据。

以下是fetchedController的代码:

NSEntityDescription *entity = [NSEntityDescription 
                               entityForName:@"Appliance" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

[fetchRequest setFetchBatchSize:20];

NSFetchedResultsController *theFetchedResultsController = 
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
                                    managedObjectContext:context sectionNameKeyPath:@"productLine.name" 
                                               cacheName:@"Root"];

部分密钥路径使用相关实体。设备<< - > PRODUCTLINE。

我正在获得表格中各节的标题:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo name];
}

这很好用,但是如果我将排序更改为“升序:是”,那么表格部分会得到错误的标题。

1 个答案:

答案 0 :(得分:4)

我自己找到了答案。事实证明,我需要通过productLine.name对结果进行排序,然后按名称对它们进行排序。所以我添加了另一个排序描述符。

NSSortDescriptor *aSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];

NSSortDescriptor *pSort = [[NSSortDescriptor alloc] initWithKey:@"productLine.name" ascending:YES];

[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:pSort, aSort, nil]];

一切都很好。