Using NSFetchedResultsController to get a random object
I woul开发者_运维知识库d like to fetch a random object from a fetch request that I am using NSFetchedResultsController
with. This is what I had:
int randIndex = arc4random() % [[_fetchedResultsController fetchedObjects] count];
randomObject = [_fetchedResultsController objectAtIndex:randIndex];
However, I don't think I'm doing this correctly, as it is causing crashes. Could someone please provide me some advice?
Try this:
int randIndex = arc4random() % [[_fetchedResultsController fetchedObjects] count];
randomObject = [[_fetchedResultsController fetchedObjects] objectAtIndex:randIndex];
The crash is because NSFetchedResultsController doesn't respond to -objectAtIndex:.
精彩评论