views:

273

answers:

3

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?

+2  A: 

I think you would need to create your objects with a randomized property then sort by that.

Andiih
Any guide on how to create randomized property?This is not creating an int property with random numbers, right?
samwize
I think you random int property will do just fine...
Niels Castle
+1  A: 

You could fetch your objects, put them in an NSMutableArray, and shuffle it, as discussed here:

http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray

No Surprises
I am using NSFetchedResultsController for iPhone's table, so i don't think i should get fetchedObjects and sort it
samwize
+4  A: 

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.

Alex Reynolds
Haha "random sort" sounds contradictory. But yea, what i want is really a sort that is random.Suggestion 1 sounds like a way to do. But I did encounter weird behaviour from tableview when mapping index path to the fetchedResults. I'll try anyway.Suggestion 2 is a hackaround. I would try not to touch my entity properties. But if all else fail, I'll try this.
samwize