如何使用CoreData随机排序 [英] How to sort randomly with CoreData
问题描述
我使用NSFetchRequest来获取一些项目,可以按热门排序,或随机。
I am using NSFetchRequest to fetch some items, which could be sorted by Popular, or Random.
按照指南,我可以很容易地使用NSSortDescriptor按照流行度对项目进行排序。
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];
但是如何随机排序?
推荐答案
有没有一个随机排序的东西?
Is there such a thing as a "random sort"?
如果您要随机排列显示通过 NSFetchedResultsController
获得的结果,请记住您正在填充表视图基于对控制器提取结果( -objectAtIndexPath:
)中的元素的 indexPath
引用。
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:
).
因此,你可以做的事情是洗刷一个 NSMutableArray
(或数组)的索引路径,编写一个方法将索引路径映射到置换索引路径。此方法将索引路径用作输入,查找数组(或多个数组)并输出一个新的索引路径作为输出。
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.
或者,您也可以为您的表格视图添加 randomizerTag
属性 Item
实体。您可以使用任何排列函数生成整数 {1 ... n}
的排列,并将这些数字保存到商店中的每个记录。保存后,您可以重新应用排序在记录的 randomizerTag
值的排序描述符。
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.
这篇关于如何使用CoreData随机排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!