A
A
agee2014-05-15 18:35:32
Objective-C
agee, 2014-05-15 18:35:32

(Core Data) How to do random sort in NSFetchedResultsController?

My task is to get objects from the database in random order.
First, I generate random ids into an NSArray and pass them as a predicate:

fetchRequest.predicate = [NSPredicate predicateWithFormat:@"(self.id IN %@)", randomIds];
// Пример содержимого массива randomIds (каждый раз разный):
// <__NSArrayM 0xd1cc4e0>(185,51,69,25,33,135,136,97,157,112,145,132,56,15,159,70,88,6,72,82)

However, because the NSFetchedResultsController requires its FetchRequest to be set to sortDescriptors, my results are always sorted:
NSSortDescriptor *sortingDescriptor = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES];
fetchRequest.sortDescriptors = @[sortingDescriptor];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                       managedObjectContext:context
                                                                         sectionNameKeyPath:nil
                                                                                  cacheName:nil];

An internet search didn't give me any sane results. How would you solve this problem? Maybe someone has already encountered and came to some kind of solution?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
S
s0L, 2014-05-16
@s0L

Well, as an option, make a field in Entity, by which you will sort and fill it with random values

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question