Your goal is to hand back the data, like this:
[[self delegate] setFirstName:_firstNameString];
But you can't do that unless you know who to send setFirstName:
to, and the compiler won't let you do it unless you guarantee that whoever you are sending setFirstName:
to can accept that message.
That is what prepareForSegue
prepares. FirstVC has declared that it adopts the passNames
protocol, which means that it implements setFirstName:
. And now you are saying:
[vc2 setDelegate:self];
...where self
is the FirstVC instance. This solves both problems at once. The SecondVC instance (vc2
) now has a delegate (the FirstVC instance), it is the right object to send the info back to, and because its delegate is declared as adopting passNames
, we know that SecondVC can actually send setFirstName:
to that delegate.
Now to the heart of your actual question: The reason for doing this in prepareForSegue
is merely that this is the only moment when the FirstVC instance and the SecondVC instance "meet" one another! There is no other moment when the FirstVC instance has a reference to the SecondVC instance so as to be able to call setDelegate
on it in the first place. If you weren't using segues and storyboards, the FirstVC would simply create the SecondVC instance directly - and would set itself as its delegate, just as you do:
SecondVC *vc2 = [SecondVC new];
UINavigationController *nav = [
[UINavigationController alloc] initWithRootViewController: vc2];
[vc2 setDelegate:self];
[self presentViewController: nav animated: YES completion: nil];
This is one reason I don't like storyboards: they muddy the story. It's all so simple and obvious when you don't use them and just do everything directly like this.