Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort randomly with CoreData

I am using NSFetchRequest to fetch some items, which could be sorted by Popular, or Random.

Following the guides, I could sort the items by popularity easily using NSSortDescriptor.

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"popularity" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [request setSortDescriptors:sortDescriptors];

But how do I sort them randomly?

like image 898
samwize Avatar asked Dec 30 '22 05:12

samwize


1 Answers

Is there such a thing as a "random sort"?

If you want to randomly permute the display of results obtained via NSFetchedResultsController, remember that you are populating your table view based on an indexPath reference to an element in your controller's fetched results (-objectAtIndexPath:).

So one thing you can do is shuffle an NSMutableArray (or arrays) of index paths, writing a method that maps an index path to a permuted index path. This method takes an index path as input, looks up the array (or arrays) and spits out a new index path as output. You use this new index path to populate your table view.

Alternatively, you can add a randomizerTag attribute to your Item entity. You use any permutation function to generate a permutation of integers { 1 ... n } and save those numbers to each record in your store. Once saved, you can refetch, applying a sort descriptor that sorts on the randomizerTag values of your records.

like image 72
Alex Reynolds Avatar answered Jan 08 '23 19:01

Alex Reynolds