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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With