How to randomly sort using CoreData

I use NSFetchRequest to retrieve some items that can be sorted using popular or random.

Following the instructions, I could easily sort items by popularity 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?

+3
source share
3 answers

Is there such a thing as "random sorting"?

If you want to randomly rearrange the display of results obtained using the NSFetchedResultsController , remember that you populate the table view based on the indexPath link to the element in the received results of your controller ( -objectAtIndexPath: .

So, one thing you can do is shuffle the NSMutableArray (or arrays) of the index paths, writing a method that maps the index path to the index permutation path. This method takes a pointer path as an input, searches for an array (or arrays), and returns a new index path as output. This new index path is used to populate the table view.

Alternatively, you can add the randomizerTag attribute to your Item object. You use any permutation function to generate the permutation of the integers { 1 ... n } and store these numbers for each entry in your store. After saving, you can restore using the sort descriptor, which sorts the randomizerTag values โ€‹โ€‹of your records.

+5
source

I think you will need to create your objects with a random property, and then sort by them.

+2
source

You can get your objects, put them in an NSMutableArray and shuffle as described here:

What is the best way to swap in NSMutableArray?

+2
source

All Articles