Apophenia Overload
Apophenia Overload

Reputation: 2504

Using NSFetchedResultsController to get a random object

I would 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?

Upvotes: 0

Views: 529

Answers (1)

lazycs
lazycs

Reputation: 1604

Try this:

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

The crash is because NSFetchedResultsController doesn't respond to -objectAtIndex:.

Upvotes: 3

Related Questions