Objective-C, Storyboard: instantiateViewController

2019-05-11 04:35发布

问题:

I have a UITableViewController with a storyboard push segue linking from the prototype cell to a detail page, a regular old UIViewController. In the storyboard, the detail ViewController has an identifier, and the segue has an identifier which is the same as the detail identifier except that the first letter is lowercase. Furthermore, the detail ViewController has a "custom class" (AttractionDetailViewController) selected in the class pulldown.

Doesn't work. The problem is that instantiateViewControllerWithIdentifier:@"AttractionDetails returns nil.

Relevant code. First the prepareForSegue method which the debugger has never entered.

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"attractionDetails"])
    {
        AttractionDetailViewController *attrDetailVC = [segue destinationViewController];
    }
}

Instead it goes into this method:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //AttractionDetailViewController *attrDetailVC = [[AttractionDetailViewController alloc] init];
    AttractionDetailViewController *attrDetailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"AttractionDetails"];

    NSIndexPath *selIndexPath = [self.tableView indexPathForSelectedRow];
    attrDetailVC.theAttraction = [attractions objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:attrDetailVC animated:YES];
}

Since instantiateViewControllerWithIdentifier returns nil it throws an exception of course. The really interesting thing is, if I use the alloc init line instead, it works, but the screen is all black.

Anyway, I've read up about this and tried a few different things and I'm still stymied. Does anyone have any suggestions?

回答1:

The problem is that you didn't instantiate your master view controller (the UITableViewController) from the storyboard, so its storyboard property is nil.