Jeff Wolski
Jeff Wolski

Reputation: 6372

How can I fetch only the top 20 objects from core data

I need to find the 20 objects most recently viewed (date-stamped) by the user. Each object has a property in the core data model called dateVisited. When the user views a particular object, the dateVisited property is assigned the current date stamp.

So, I have a 'Recent' view that shows the 20 most recently viewed objects. I'm currently using the code below to fetch and sort the data.

            [fetchRequest setEntity:[NSEntityDescription entityForName:@"object" inManagedObjectContext:self.moc]];
            predicate = [NSPredicate predicateWithFormat:
                                      @"objectNumber contains[cd] %@", searchTerm]; 

            [fetchRequest setPredicate:predicate];
            NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"dateVisited" ascending:NO];
            NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
            [fetchRequest setSortDescriptors:sortDescriptors];
            [sortDescriptors release];
            [sortDescriptor release];

            NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
                                                      initWithFetchRequest:fetchRequest
                                                      managedObjectContext:self.moc
                                                      sectionNameKeyPath:nil
                                                      cacheName:nil];
            [fetchRequest release];

The code returns the set of 3,000 objects in order, and I display the first 20. However, it's sorting all 3,000 objects and takes time to do so. It would be far more efficient if the sort only kept track of the 20 'top' encountered objects and dropped each one along the way if that object already was not in the top 20 encountered so far.

So my question is this: Is there a way to do a fetch/sort that only keeps track of the running top 20 objects?

Upvotes: 0

Views: 145

Answers (1)

Mundi
Mundi

Reputation: 80265

[fetchRequest setFetchLimit:20];

Cheers!

Upvotes: 5

Related Questions