[英]core data fetch last 20 records in ascending order?
In my app i've some records in core data
and i want to fetch last 20 records in ascending order ie. 在我的应用程序中,我在
core data
有一些记录,我想按升序获取最后20条记录,即。 if there is 30 records than i want to fetch records from 11 to 30 in ascending order - 如果有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
}
but it gives me first 20 records in ascending order and if i change to 但它按升序给我前20条记录,如果我改为
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:@"messageId" ascending:NO];
then i got last 20 records but that was in ascending order?Any suggestion would be appreciated. 然后我有最后20条记录,但是按升序排列?任何建议都会受到赞赏。
cant you just set this offset? 你不能设置这个偏移?
//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]
NSFetchRequest
does not provide a method for that. NSFetchRequest
没有提供相应的方法。 You have to fetch 20 records in descending order and then reverse the resulting data array: 您必须按降序获取20条记录,然后反转生成的数据数组:
dataArray = [[dataArray reverseObjectEnumerator] allObjects];
If this is for display in a table view, then instead of actually reversing the data array you could adapt the cellForRowAtIndexPath
method to display the object 如果这是在表视图中显示,那么您可以调整
cellForRowAtIndexPath
方法来显示对象,而不是实际反转数据数组
dataArray[dataArray.count - 1 - indexPath.row]
instead of 代替
dataArray[indexPath.row]
you can use - 您可以使用 -
//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
}
Happy coding :P 编码愉快:P
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.