如何以相反的方向对获取的请求结果进行排序?

时间:2013-01-28 18:21:35

标签: ios core-data

我有实体消息。每条消息都包含时间戳。我想一次只显示20条最后的消息,从最旧的消息到最新消息。

要获得最后20个,我会执行以下代码

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Message" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
[fetchRequest setFetchLimit:20];
NSSortDescriptor *timeDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"time" ascending:NO] autorelease];
[fetchRequest setSortDescriptors:timeDescriptor];
NSFetchedResultsController *aFetchedResultsController = [[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"data" cacheName:nil] autorelease];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;

但结果我想显示升序:是。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

难道你不能只取总数#并减去当前行来获得反向排序。所以0 - > 20,1 - > 19,...... 20 - > 0.假设您使用的是带有1个部分的tableView,代码看起来像(未经测试):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:0];
NSInteger reverseRow = [sectionInfo numberOfObjects] - indexPath.row - 1;
NSIndexPath *reverseIndexPath = [NSIndexPath indexPathForRow:reverseRow inSection:indexPath.section];    
id myObject = [self.fetchedResultsController objectAtIndexPath:reverseIndexPath];
}