Search code examples
iosuitableviewuisearchbarnsindexpathuisearchbardelegate

Open a detailViewController after use of UISearchBar


I have a UISearchBar to search some data in a tableView and then, after searching, selecting a row to open a detailViewController . To do this it is necessary that the lines keep the index path and do not change the initial indexPath after the search, because otherwise I can not find the right elements in the database. How do I keep the initial indexPath? Are there any other methods?

 -(void) searchExpositorsTableView{
      [searchResult removeAllObjects]; 
      //In this array there are the elements resulted after research

      for (Database *currow in self.mutableArray){
         NSLog(@"list of expositors %@", self.mutableArray);

        NSRange titleResultsRange = [currow.name rangeOfString:self.searchBar.text options: NSCaseInsensitiveSearch];;
          if (titleResultsRange.length >0) {
                [searchResult addObject:currow.name];
                /*While I build this new array every indexPath change and the database
                  can not track down the original items*/
          }
        }

    NSLog(@"%@", searchResult);
   }

   -(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{

      if(canSelectRow){

           NSLog(@"%d", indexPath.row);
           /*the indexPath is new and the database can not track down the original items*/
           return indexPath;

       }else{
        return nil;
       }
    NSLog(@"%d", indexPath.row);
 }

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   //Open wrong element
 }

Solution

  • DO this

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
        if(searching) // where searching is boolean YES is searching, NO if not searched any element
        {
            //get your data from searchResults and open detailViewController
            Database *currow = [searchResults objectAtIndex:indexPath.row];
            DetailViewController = detailView = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
            [self.navigationController pushViewController:detailView animated:YES];
            [detailView release];
        }
        else
        {
            //get your data from self.mutableArray and open detailViewController
            Database *currow = [self.mutableArray objectAtIndex:indexPath.row];
            DetailViewController = detailView = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
            [self.navigationController pushViewController:detailView animated:YES];
            [detailView release];
        }
    
    }