Problems passing indexPath.row using prepareForSegue with UISearchBar

I have from time to time to get all this basic data, Storyboard, trio UISearchBar, working together as it should. Finally, having successfully built the table using Core Data, dry the elements with the search text and change readyForSegue, there is one more hiccup ...

When I click on any element of the table to go to the detailed view, everything is fine in the unfiltered table. PrepareForSegue is called and the part is displayed in detail.

When I do a search, my table is filtered (now I will filter the array, not the second NSFetchedResultsController, but not due to the lack of attempts!).

When I click on an item in a filtered list, the prepareForSegue method is called and a detailed view is displayed, however it always pulls the details from the first item in the list!

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

I am assuming that prepareForSegue code is the problem (maybe wrong?). 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!

+6
source share
1 answer

Thanks to Phillip Mills for the answer:

just needed 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; 
+12
source

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


All Articles