How do I include section information in indexPathForSelectedRow

232 views Asked by At

I have a table with sections, populated by an array which is comprised of four arrays. How do I modify the indexPathForSelectedRow statements in the prepare for segue method to include section information?

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([[segue identifier]isEqualToString:@"plantSaveSegue"])
    {
        NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
        DetailViewController *grassType = [segue destinationViewController];

        //grassType.selectedPlant = [grassArray objectAtIndex:selectedRowIndex.row];
        grassType.selectedPlant = [plantArray objectAtIndex:selectedRowIndex.row];
    }
}

This works perfectly for one section, but what do I do for four sections?

2

There are 2 answers

2
Shabarinath Pabba On

Declare 2 NSIntegers in the .h file

NSInteger selectedSection;
NSInteger selectedRow;

and now in your viewDidLoad(), initialize these to "-1"

selectedSection = -1;
selectedRow = -1;

Now in

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


selectedSection = indexPath.section;
selectedRow = indexPath.row;

//Now performSegue here
}

After that

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([[segue identifier]isEqualToString:@"plantSaveSegue"])
    {
        NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
        DetailViewController *grassType = [segue destinationViewController];

        if(selectedSection == 0){
             grassType.selectedPlant = [firstArray objectAtIndex:selectedRow];}
        else if(selectedSection == 1){
             grassType.selectedPlant = [secondArray objectAtIndex:selectedRow];}
        else if(selectedSection == 2){
             grassType.selectedPlant = [thirdArray objectAtIndex:selectedRow];}
        else if(selectedSection == 3{
             grassType.selectedPlant = [fourthArray objectAtIndex:selectedRow];}

    }
}

Hope This Helps

0
user1698875 On

Thanks for all the help and guidance. The answer was distressingly simple, type in the complete and correct path for the appropriate item in the table. See below:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier]isEqualToString:@"plantSaveSegue"])
{
    NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
    DetailViewController *grassType = [segue destinationViewController];
    grassType.selectedPlant = [[plantArray objectAtIndex:selectedRowIndex.section]objectAtIndex:selectedRowIndex.row];
}
}