Search code examples
ioscore-datanspredicatensfetchedresultscontrollernssortdescriptor

Random results from NSFetchedResultsController


I have some data in my entity. How can I get all entries in a random order. ie I wanna shuffle all entries again and again.

I found solution of this question here: Shuffling the results from an NSFetchedResultsController. But I would like to get NSFetchedResultsController with results. Any ideas? Maybe using NSPredicate or NSSortDescriptor?


Solution

  • Subclass NSSortDescriptor to change the default sorting behavior. Something like this should work:

    @interface RandomSortDescriptor : NSSortDescriptor 
    @end
    
    @implementation RandomSortDescriptor
    
    - (id)copyWithZone:(NSZone*)zone
    {
        return [[[self class] alloc] initWithKey:[self key] 
                               ascending:[self ascending] selector:[self selector]];
    }
    
    - (id)reversedSortDescriptor
    {
        return [[[self class] alloc] initWithKey:[self key] 
                               ascending:![self ascending] selector:[self selector]];
    }
    
    - (NSComparisonResult)compareObject:(id)object1 toObject:(id)object2 
    {
        NSUInteger random = arc4random_uniform(3);
        switch (random)
        {
           case 0:
              return NSOrderedSame
           case 1:
              return NSOrderedDescending;
           case 2:
              return NSOrderedDescending;
         }
    }
    
    @end