2
votes

Please direct me to the right way.

I implemented this code to fetch my objects:

- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    NSPredicate *predicate = nil;

    if (self.selectedCategory)
    {
        predicate = [NSPredicate predicateWithFormat:@"ANY category_ids.category_id == %@", self.selectedCategory];
    }

    _fetchedResultsController = [EyeArtist fetchAllGroupedBy:nil withPredicate:predicate sortedBy:@"artist_id" ascending:NO delegate:self];

    return _fetchedResultsController;
}

So when app run the at first time fetch works without predicate, so at second time I need new fetch with predicate.

I tap on the button and set string self.selectedCategory, but I don't know how to refetch data from - (NSFetchedResultsController *)fetchedResultsController;

So I suppose it has to be like execute new request for fetchedResultsController instance.

2

2 Answers

5
votes

After changing the search criteria, you have to set the instance variable self.fetchedResultsController to nil, so that the next call to the "lazy getter" function creates a new FRC with the changed predicate. Something like this:

self.fetchedResultsController = nil;
[self.fetchedResultsController performFetch:&error];
[self.tableView reloadData];
0
votes

This is the pattern I use for where a fetch controller needs a property:

- (void)setSelectedCategory:(id)selectedCategory{
    if(selectedCategory == _selectedCategory){
         return _selectedCategory
    }
    _selectedCategory = selectedCategory;
    self.fetchedResultsController = nil;
    if(self.isViewLoaded){
        [self.tableView reloadData]; // but better to put this in an update views method that you can also call from viewDidLoad.
    }
}

- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    id selectedCategory = self.selectedCategory;
    // Only need this if a category is required.
    if(!selectedCategory){
        return nil;
    }
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY category_ids.category_id == %@", selectedCategory];
    _fetchedResultsController = [EyeArtist fetchAllGroupedBy:nil withPredicate:predicate sortedBy:@"artist_id" ascending:NO delegate:self];
    return _fetchedResultsController;
}