使用NSFetchedResultsController获取随机对象

时间:2011-03-27 05:31:29

标签: iphone objective-c nsfetchedresultscontroller

我想从我正在使用NSFetchedResultsController的抓取请求中获取随机对象。这就是我所拥有的:

int randIndex = arc4random() % [[_fetchedResultsController fetchedObjects] count];
randomObject = [_fetchedResultsController objectAtIndex:randIndex];

但是,我认为我没有正确地执行此操作,因为它会导致崩溃。有人可以给我一些建议吗?

1 个答案:

答案 0 :(得分:3)

试试这个:

int randIndex = arc4random() % [[_fetchedResultsController fetchedObjects] count];
randomObject = [[_fetchedResultsController fetchedObjects] objectAtIndex:randIndex];

崩溃是因为NSFetchedResultsController没有响应-objectAtIndex:。