ios - NSFetchedResultsController的随机结果

标签 ios core-data nspredicate nsfetchedresultscontroller nssortdescriptor

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

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

最佳答案

子类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

关于ios - NSFetchedResultsController的随机结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17469891/

相关文章:

ios - 在 Swift 2.3 中关闭 UIAlertController 键盘

ios - 如何创建一个新的文本文件以写入 objective c ipad app

ios - CoreLocation 不适用于 iOS 8 上的 Adhoc Distribution

ios - Simperium 和用户组

swift - 如何一次将数据发送到两个属性中?

ios - 快速点击按钮时添加行或文本字段

ios - 具有多种关系的核心数据 NSPredicate

ios - CoreData 获取请求 - 获取所有有关系的对象

iphone - NSPredicate 在内部使用任何搜索算法?

iphone - 为什么我的 UISearchController 很慢?