我正在使用arc 4随机从我的fetchresultscontroller中选择一个随机条目,但我需要省略某个类别的所有条目。该列是“类别”,我不希望随机选择包括类别“Category2”。以下是我目前的代码,任何帮助将不胜感激!
- (NSIndexPath *)randomIndexPath
{
NSInteger randomSection = arc4random_uniform([[fetchedResultsController sections] count]);
id <NSFetchedResultsSectionInfo> sectionInfo =
[[fetchedResultsController sections] objectAtIndex:randomSection];
NSInteger randomIndex = arc4random_uniform( [sectionInfo numberOfObjects]);
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:randomIndex inSection:randomSection];
return indexPath;
}
- (IBAction)displayRandomEntry:(id)sender {
if([[fetchedResultsController sections] count] <= 0)
return;
NSIndexPath *indexPath = [self randomIndexPath];
[self.myTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
id object = [fetchedResultsController objectAtIndexPath:indexPath];
RandomEntryDetailVC * controller;
controller = [self.storyboard instantiateViewControllerWithIdentifier:@"ShowRandomEntryDetailVC"];
controller.currentItem = object;
[self.navigationController pushViewController:controller animated:YES];
}
答案 0 :(得分:1)
在任何随机数生成器中,避免特定值(或值的范围)的方法是选择一个数字,如果该数字不在您喜欢的范围内,则选择另一个数字。继续,直到你得到一个你喜欢的号码。虽然理论上这是非暂停的,但在实践中,对于任何足够大的子集,它都会很快停止。