NSFetchedResultsController loads all data and poor performance

I have a large database with over 8000 entries. I want to download and list in a tableview . I used NSFetchedResultsController . It works great except for poor performance. I found a tutorial here

And added my performFetch: method in the viewDidLoad: method. But loading takes 2-3 seconds.

Here is my code.

 - (void)loadFetchResultsController { NSError *error; if (![[self fetchedResultsController] performFetch:&error]) { // Update to handle the error appropriately. NSLog(@"Error occurs while fetching the foods with fetch results controller %@, %@", error, [error userInfo]); exit(-1); } } - (NSFetchedResultsController *)fetchedResultsController { if (isSearching) { [NSFetchedResultsController deleteCacheWithName:@"SearchResults"]; } NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Food" inManagedObjectContext:_managedObjectContext]; NSPredicate *hiddenPredicate = [NSPredicate predicateWithFormat:@"hidden == %@",[NSNumber numberWithBool:NO]]; if (isSearching) { hiddenPredicate = [NSPredicate predicateWithFormat:@"(hidden == %@) AND (name contains[cd] %@ OR foodDescription contains[cd] %@)",[NSNumber numberWithBool:NO], searchTerm,searchTerm]; } [fetchRequest setEntity:entity]; [fetchRequest setPredicate:hiddenPredicate]; NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]]; [fetchRequest setFetchBatchSize:20]; NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext sectionNameKeyPath:@"name.stringGroupByFirstInitial" cacheName:(isSearching) ? @"SearchResults" : @"Root"]; _fetchedResultsController = theFetchedResultsController; _fetchedResultsController.delegate = self; return _fetchedResultsController; } 

I used the tools and found out that calling the executeFetch: method loads all the data for the first time when viewDidLoad: called.

enter image description here

My food data model is this:

enter image description here

Any idea to improve performance and get rid of the delay .. Any help would be appreciated.

+4
source share
1 answer

I believe that you need to set the extraction limit for your sample request, not just the batch size. Try calling [fetchRequest setFetchLimit: 20]; and see if that helps. This should lead to the first 20 entries. Then, when the user scrolls your data, make additional fetch requests to get more data.

0
source

Source: https://habr.com/ru/post/1486228/


All Articles