user6631218
user6631218

Reputation:

How to get indexPath when I search data in the function that prepareForSegue

I have a problem.
I have a tableView and searchController.
When I search "C",I get two data that title of name have "C".
But when I press the cell, the detailView present wrong infomation for me.

NSArray *searchResult;
UISearchController *mysearchController;


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

if ([segue.identifier isEqualToString:@"getDetail"]) {

    if (searchResult != nil) {

        DetailViewController *detailViewController = segue.destinationViewController;

        NSIndexPath *indexPath =  [searchResult..............];
        NSDictionary *item = searchResult[indexPath.row];
        detailViewController.detailName = item[@"name"];
        detailViewController.detailLocation = item[@"address"];


    }else{

        DetailViewController *detailViewController = segue.destinationViewController;

        NSIndexPath *indexPath = self.listTableView.indexPathForSelectedRow;
        NSDictionary *item = self.InfoArray[indexPath.row];
        detailViewController.detailName = item[@"name"];
        detailViewController.detailLocation = item[@"address"];

    }
  }

}

Thanks!

Upvotes: 0

Views: 155

Answers (1)

Ravi B
Ravi B

Reputation: 1592

You need to pass the Indexpath in didSelectRowAtIndexPath delegate method of UITableview. So your code look like this,

Sample Code:

NSArray *searchResult;
UISearchController *mysearchController;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //code here for select the cell amd put the name of the SegueIdentifier
    [self performSegueWithIdentifier:@"getDetail" sender:indexPath];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    if ([segue.identifier isEqualToString:@"getDetail"]) {

        if (searchResult != nil) {

            DetailViewController *detailViewController = segue.destinationViewController;

            NSIndexPath *indexPath = (NSIndexPath *) sender;
            NSDictionary *item = searchResult[indexPath.row];
            detailViewController.detailName = item[@"name"];
            detailViewController.detailLocation = item[@"address"];


        }else{

            DetailViewController *detailViewController = segue.destinationViewController;

            NSIndexPath *indexPath =  (NSIndexPath *) sender;
            NSDictionary *item = self.InfoArray[indexPath.row];
            detailViewController.detailName = item[@"name"];
            detailViewController.detailLocation = item[@"address"];

        }
    }

}

Hope it works :)

Let me know if any issue.

Upvotes: 2

Related Questions