在我的应用程序中我在core data
中有一些记录,我想按升序获取最后20条记录,即如果有30条记录,那么我想按升序从11到30获取记录 -
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Messages" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchLimit:20];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:@"messageId" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"((userId == %@) && (frndId == %@) )",uid, fid];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray* dataArray = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
for (Messages* msg in dataArray) {
//code here
}
但它按升序给我前20条记录,如果我改为
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:@"messageId" ascending:NO];
然后我得到了最后20条记录,但这是按升序排列的?任何建议都会受到赞赏。
答案 0 :(得分:9)
你不能设置这个偏移量吗?
//assume it fits an nsinteger
NSInteger count = [managedObjectContext countForFetchRequest:fetchRequest /*the one you have above but without limit */ error:&error];
NSUInteger size = 20;
count -= size;
[fetchRequest setFetchOffset:count>0?count:0];
[fetchRequest setFetchLimit:size];
NSArray* dataArray = [managedObjectContext executeFetchRequest:fetchRequest error:&error]
答案 1 :(得分:3)
NSFetchRequest
没有为此提供方法。您必须按降序获取20条记录,然后反转生成的数据数组:
dataArray = [[dataArray reverseObjectEnumerator] allObjects];
如果这是用于在表视图中显示,那么而不是实际反转数据数组
您可以调整cellForRowAtIndexPath
方法来显示对象
dataArray[dataArray.count - 1 - indexPath.row]
而不是
dataArray[indexPath.row]
答案 2 :(得分:3)
你可以使用 -
//your code as it is till this line but with
//NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:@"messageId" ascending:NO];
NSArray* dataArray = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
NSArray *sortedArray;
sortedArray = [dataArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first = [(Messages*)a messageId];
NSString *second = [(Messages*)b messageId];
return [first compare:second];
}];
for (Messages* msg in sortedArray) {
//your code
}
快乐编码:P