我有实体消息。每条消息都包含时间戳。我想一次只显示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;
但结果我想显示升序:是。有没有办法做到这一点?
答案 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];
}