Trouble passing indexPath.row with prepareForSegue with UISearchBar

uisearchbaruistoryboardsegueuitableview

I'm having a dickens of a time getting this whole Core Data, Storyboard, UISearchBar trio working together as it should. Having finally successfully built the table with Core Data, narrow the items with a Search Text, and modified prepareForSegue, there is still one hiccup…

When I click on any item in the table to go to the detail view, all is fine in the unfiltered table. PrepareForSegue is called and the detail appears perfectly.

When I search, my table is filtered (I'm going to filtered array option for now instead of a second NSFetchedResultsController, but not for lack of trying!).

When I click on an item in the filtered list, prepareForSegue is called and the detail view is pushed, however, it always pulls the detail from the first item in the list!

For example, if I searched for "c" and the list was narrowed to "Charlie" and "Cookie", when I select "Charlie" I see the detail view for "Charlie". When I select "Cookie", I, unfortunately, also see the detail view for "Charlie"

I'm making the assumption that the prepareForSegue code is the issue (maybe incorrectly?). Here is the code:

    SampleTVC *sampleDetailTVC = segue.destinationViewController;
    sampleDetailTVC.delegate = self;

    // Store selected Role in selectedRole property
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
  //  self.selectedRole = [self.fetchedResultsController objectAtIndexPath:indexPath];
    if (savedSearchTerm){
        self.selectedRole = [self.searchResults objectAtIndex:indexPath.row];
    } else {
        self.selectedRole = [self.fetchedResultsController objectAtIndexPath:indexPath];
    }
    NSLog(@"Passing selected role (%@) to SampleTVC", self.selectedRole.name);
    sampleDetailTVC.role = self.selectedRole;

Any help would be appreciated!

Best Answer

Thanks to Phillip Mills, for the answer:

just simply had to add:

    indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];

full sample:

    SampleTVC *sampleDetailTVC = segue.destinationViewController;
    sampleDetailTVC.delegate = self;
     // Store selected Role in selectedRole property
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    //  self.selectedRole = [self.fetchedResultsController objectAtIndexPath:indexPath];
    if (savedSearchTerm){
         indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
    self.selectedRole = [self.searchResults objectAtIndex:indexPath.row];
    } else {
        self.selectedRole = [self.fetchedResultsController objectAtIndexPath:indexPath];
     }
    NSLog(@"Passing selected role (%@) to SampleTVC", self.selectedRole.name);
    sampleDetailTVC.role = self.selectedRole;
Related Topic