user1904273
user1904273

Reputation: 4764

IOS/xcode: Searchbar for TableView with NSFETched Results Controller

Hi I am trying to implement a search bar function for a table view using core data and NSFetchedResults Controller.

Quite a number of answers on SO suggest using a predicate for search using something like the following code:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if ([searchText length] == 0) {
        _fetchedResultsController = nil;
    }
    else {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", searchText];
        [[_fetchedResultsController fetchRequest] setPredicate:predicate];
        [[_fetchedResultsController fetchRequest] setFetchLimit:50];
    }

    NSError *error;
    if (![[self fetchedResultsController] performFetch:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }

    [[self tableView] reloadData];
}

I have also tried variations of this. In every case, however, I'm having the same problem.

First, when you search, it says no results. Also if you type in a few letters and hit the x, you get a grayed out screen and if you click again, you get the normal table view.

However, after typing in a letter and seeing "No Results" if you click cancel you get the results you should have gotten. Once that happens you cannot get back to the full tableview without rebuilding the project.

The only idea I have so far is it might have something to do with _fetchedResultsController vs fetchedResultsController (the property in this source file is ftchedResultsController without the underscore) but changing those only throws error messages.

Thank you for any suggestions on what could be causing this.

Upvotes: 0

Views: 175

Answers (1)

Mundi
Mundi

Reputation: 80265

You have two table views, one from the search and the main one from the main table. You should disable the search controller's table view if you want to keep showing your main table view with the filter implied by the search.

self.searchResultsController.active = NO;

You could set this every time the search bar would otherwise set this to YES, like in textDidChange. In your FRC getter, you check for any string in the search bar and add a predicate if necessary. In textDidChange you nil out the FRC and reloadData. That's it.

Upvotes: 1

Related Questions