Question

How can I change my code so it could run on different queue then the main queue:

- (NSFetchedResultsController *)fetchResultController{

    if (_fetchResultController != nil) {            
        return _fetchResultController;
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSManagedObjectContext *context = [self managedObjectContext];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Recipes"
    inManagedObjectContext:context];

    [fetchRequest setEntity:entity];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"headline"
    ascending:YES];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(category = %@)",_categoryToShown];

    [fetchRequest setPredicate: predicate];

    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];

    _fetchResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];

    _fetchResultController.delegate = self;

    return _fetchResultController;    
}
Was it helpful?

Solution

A NSFetchedResultsController works with UITableViews or UICollectionViews. These are part of the UIKit and so they should be touched only on the main queue.

In addition NSFetchedResultsController has been developed to get data through lazy loading features (data batches) in order to reduce the memory footprint.

So, what's your goal? Why do you need to change the queue you are running on?

Edit 1

when i click a button in my UI its segue to table view that fill the data according to this fetch request.i want that when i click the button its automatically segue to the table view so i need to write this code with multithreading

If you want to achieve what you wrote in the comment you should create a fetch request and execute it in a background thread..In this way when you'll land on the segue results will be available on internal cache of the persistent store coordinator. This technique is called as "warming up the cache" by Marcus Zarra (CoreData weird behavior when data are loaded on background thread). With the following approach the usage of NSFetchedResultsController is not useful. So, before taking this approach why don't you try to play a bit with

[fetchRequest setFetchBatchSize:20];

If the table (or collection) will display 10 elements, 20 as batch size it's ok. Anyway Instruments is your friend.

In addition, I really suggest to have a look to Core Data performance is a balance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top