1

我的实体中有一些数据。如何以随机顺序获取所有条目。即我想一次又一次地洗牌所有条目。

我在这里找到了这个问题的解决方案:Shuffling the results from an NSFetchedResultsController。但我想得到NSFetchedResultsController结果。有任何想法吗?也许使用NSPredicateor NSSortDescriptor

4

1 回答 1

3

NSSortDescriptor更改默认排序行为的子类。像这样的东西应该工作:

@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
于 2014-09-07T15:25:29.280 回答