1

So lets suppose i have this in DB:

a,b,c,d,e,f (ordered by date)

And i want to fetch them in order by date and get only the last 2 in every request

So i would get: e,f

The problem is that if i use the fetchLimit, I get the first ones of my ordered fetch not the last ones. I could calculate the offset every time the NSFRC changes. Also i need to use a NSFRC.

Does any one knows a better solution?

In SQL my query would be:

select * from (select * from tblmessage order by sortfield ASC limit 10) order by sortfield DESC;

This is what i want but for IOS: Android SQLite Query - Getting latest 10 records

Community
  • 1
  • 1
João Nunes
  • 3,751
  • 31
  • 32

1 Answers1

1

Just change the sort order and set the fetch limit as desired. If you need to, reverse the result.

fetchRequest.sortDescriptors = 
 @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO]];
fetchRequest.fetchLimit = 2;

NSArray *final result = [[fetchedObjects reverseObjectEnumerator] allObjects];

Of course, I see that your FRC problem is not solved this way. If you have a flat FRC i.e. without sections, you could just manipulate the index of your fetchedObjects array (substituting every index i with count-1-i.

Maybe the best way is to execute a quick fetch before returning the FRC in order to determine the fetchOffset. It would be very efficient I think by using countForFetchRequest.

NSInteger count = [self.managedObjectContext countForFetchRequest:request];
fetchRequest.sortDescriptors = 
  @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]];
fetchRequest.fetchOffset = count-2; 

If you follow the Apple Core Data template pattern of a lazily loading FRC, the performance should be beyond reproach.

Mundi
  • 79,884
  • 17
  • 117
  • 140
  • I used the first approach as you mentioned :) Now I'm converting to the second. But I guess there is a better option for this. Like in SQL a nested query would solve this problem easily. – João Nunes Nov 07 '13 at 09:01
  • I ended up using the second approach where i make a count for every refresh of the fetched objects. The good thing is that once the offset is set it will be keep even if there are more objects in DB later. You don't need to add 1 every time there is a new objet :) – João Nunes Nov 07 '13 at 09:25