不要使用您的 NSFetchedResultsController 作为您的表视图数据源,而是创建一个 NSArray,当用户使用基于获取的结果的数组内容更改您的分段控件更改排序顺序时设置它。然后只需使用标准数组排序进行排序。像这样的东西:
- (IBAction)segmentChanged:(id)sender
{
// Determine which segment is selected and then set this
// variable accordingly
BOOL ascending = ([sender selectedSegmentIndex] == 0);
NSArray *allObjects = [fetchedResultsController fetchedObjects];
NSSortDescriptor *sortNameDescriptor =
[[[NSSortDescriptor alloc] initWithKey:@"name"
ascending:ascending] autorelease];
NSArray *sortDescriptors = [[[NSArray alloc]
initWithObjects:sortNameDescriptor, nil] autorelease];
// items is a synthesized ivar that we use as the table view
// data source.
[self setItems:[allObjects sortedArrayUsingDescriptors:sortDescriptors]];
// Tell the tableview to reload.
[itemsTableView reloadData];
}
因此,我使用的排序描述符称为“名称”,但您可以将其更改为要在获取的结果中排序的字段的名称。此外,我引用的项目 ivar 将是您的新表视图数据源。您的表视图代表现在将是这样的:
- (NSInteger)tableView:(UITableView*)tableView
numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Get your table cell by reuse identifier as usual and then grab one of
// your records based on the index path
// ...
MyManagedObject *object = [items objectAtIndex:[indexPath row]];
// Set your cell label text or whatever you want
// with one of the managed object's fields.
// ...
return cell;
}
不确定这是否是最好的方法,但它应该有效。