Xcode segue似乎在选择表格单元格之前发生,但应该在之后发生

时间:2012-07-23 12:16:50

标签: objective-c xcode uiviewcontroller xcode4.3 segue

我正在尝试使用带有表视图的UIViewController(视图控制器)将数据发送到另一个UIViewController(详细视图控制器)。我的代码如下所示:

//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...
}

构建应用程序后,我转到View Controller并选择一个表格单元格转到详细视图控制器。这是我的输出日志:

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

从这看起来似乎在原始VC的viewDidLoad之前调用了详细视图didSelectRowAtIndexPath,尽管我显然希望后者首先发生以便变量正确传递。我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

是的,当我第一次遇到它时,这似乎非常奇怪,但也就是它的方式。

诀窍是在prepareForSegue:sender:而不是didSelectRowAtIndexPath:中完成工作。这样,您就可以将目标控制器作为segue的目的地。

(尽管如此,你的代码确实看起来有点困惑,无论你是在推动控制器还是让segue这样做。)