1

我有实体消息。每条消息都包含时间戳。我想一次只显示 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;

但在结果中我想显示升序:YES。有什么办法吗?

4

1 回答 1

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];
}
于 2013-01-28T23:51:27.283 回答