longway
longway

Reputation: 181

How to reorder the fetched results for display?

I have a tableview which is managed by a NSFetchedResultController. Since I want to fetch the most recently added record , I set the controller as below:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timeStamp >= %@",someDate];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
request.sortDescriptors = [NSArray arrayWithObject:descriptor];
request.fetchLimit = 100;

So,the results will be ordered by time descending. But I also want the results to be placed in tableview by time ascending .
How Do I re-order the results ?

Put the results into another array and reorder them and do the same thing every time after the fetch results is updated?

Upvotes: 3

Views: 378

Answers (2)

isaac
isaac

Reputation: 4897

Your predicate constrains the result set to entities with a timeStamp greater than or equal to someDay.

Your sort descriptor informs the fetch request as to which records should be retrieved, as well as actually sorts/presents them in the order specified.

Your fetch limit dictates that no more than 100 entities will be returned.

If you have 1000 matches, and sortAscending is YES, then you'll get back the oldest record that is newer than timeStamp, followed by the second oldest. If sortAscending is NO, then you will get back the newest record that is newer than timeStamp, followed by the second newest, moving back towards the oldest record that is newer than timeStamp (until you hit the 100th oldest, if it exists).

UIableViews and NSFetchedResultsControllers work together very naturally. As long as you don't go out of your way to change the way NSIndexPaths are being handled, you basically get ordering, sections, and insert/delete actions handed to you when you have a table view backed with a fetched results controller. There is no need to try to reorder the result set in a case like this - tell CoreData what you want, how much, and in what order, and you'll get it.

To have your results as (as best I can tell) you expect, you simply need to modify your sort descriptor to reflect how you actually want the records sorted. In this case, with ascending set to YES:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timeStamp >= %@",someDate];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:descriptor];
request.fetchLimit = 100;

And that should do it. There's no need to reverse-order the set in this case.

Upvotes: 0

NSPunk
NSPunk

Reputation: 502

Put your results in an array... then if you want to reverse it, setting Ascending YES, reverse your array:

NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];

i believe it's the easiest way to do it, by not fetching all the time!

Upvotes: 1

Related Questions