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开发者_如何学JAVA 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.
I think you would need to create your objects with a randomized property then sort by that.
You could fetch your objects, put them in an NSMutableArray
, and shuffle it, as discussed here:
What's the Best Way to Shuffle an NSMutableArray?
精彩评论