lemontwist
lemontwist

Reputation: 301

Xcode segue seems to be happening before selecting table cell, but should happen after

I am attempting to use a UIViewController (View Controller) with a table view to send data to another UIViewController (Detail View Controller). My code looks like this:

//ViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *detail = [self.storyboard instantiateViewControllerWithIdentifier:@"grapedetail"];
    detail.grape = [self.grapes objectAtIndex:indexPath.row];
    currentGrape = [self.grapes objectAtIndex:indexPath.row];
    NSLog(@"%@",currentGrape.searchName);
    [self.navigationController pushViewController:detail animated:YES];
    [self performSegueWithIdentifier:@"toGrapeDetail" sender:self];
}

//DetailViewController.m
- (void)viewDidLoad
{
    //obtain grape from table view
    //grape = ((ViewController *)self.presentingViewController).currentGrape; //I have also tried this method for obtaining the variable with the same result
    NSLog(@"Detail view says: %@",grape.searchName);
    //etc...
}

After I build the app I go to the View Controller and select a table cell to go to the Detail View Controller. Here is my output log:

2012-07-23 08:13:27.430 GrapeKeeper[593:f803] Detail view says: (null)
2012-07-23 08:13:27.432 GrapeKeeper[593:f803] Alarije

From this it seems that the detail view viewDidLoad is being called before the original VC's didSelectRowAtIndexPath, even though I clearly want the latter to happen first so that the variable passes correctly. What can I do to fix this?

Upvotes: 0

Views: 395

Answers (1)

Phillip Mills
Phillip Mills

Reputation: 31016

Yes, this seemed extremely weird when I first encountered it, but also just the way it is.

The trick is to do the work in prepareForSegue:sender: instead of didSelectRowAtIndexPath:. That way, you have the target controller as the segue's destination.

(Though, your code does look a bit confused concerning whether you're pushing the controller or letting the segue do it.)

Upvotes: 1

Related Questions