prepareForSegue and delegates

2020-06-12 03:39发布

问题:

I have an application with two segues. In one of the segues, the current view controller becomes a delegate and the other does not.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"MoreOptions"]) {
        UINavigationController *navigationController = segue.destinationViewController;
        MoreOptionsViewController *controller = (MoreOptionsViewController *)navigationController.topViewController;
        controller.delegate = self;
    } else if ([segue.identifier isEqualToString:@"FullStoryView"]) {
        SingleStoryViewController *detailViewController = segue.destinationViewController;
        detailViewController.urlObject = sender;
    }
}

All of this is working fine, but I would like to try and understand the code better. What I don't understand is that I have to get a reference to the MoreOptionsViewController by grabbing it from navigationController.topViewController rather than simply getting it from segue.destinationViewController like I do in the second if condition. Is it because I'm setting the current view controller (self) as the delegate? Again, I'm not trying to solve a problem, just trying to get a better understanding of what's going on.

回答1:

Take a look at your storyboard and it should be evident why this is the case. You have embedded MoreOptionsViewController in a UINavigationController and connected a segue to the navigation controller, thus making it the destinationViewController. This is fairly common.



回答2:

The delegate is largely irrelevant in the context of your question.

Your first segue's destination is a navigation controller, which contains the view controller you are really interested in. Therefore to get to that view, you need to go through the navigation controller since that won't have any properties you are interested in setting.

Your second segue goes directly to a single view controller, so you can access it directly.