Sending data using prepare(for:sender:)

Hello,
I’ve been making my own little projects based on concepts I’ve picked up from iOS Apprentice(tables). Such as sending data around using prepare(for:sender:). Here’s a problem I ran into…

ViewController#1 has a textField which’ll be used to get a String from the user. Then it sends the String directly to ViewController#2’s textField. This causes problems (unwraps a nil where a value is expected).

The issue was solved by having sender send the value to a ViewController#2 instance property, then assign that value to ViewController#2 textField.text property in a method like viewWillLoad.

My question is basically:
Do View objects get instantiated AFTER instance properties? And if not why else would the above fix work?

My understanding (feel free to correct me if I’m wrong) is it has to do with the view controller’s lifecycle. The IBOutlets aren’t connected until the loadView method is called (internally) on the view controller.

So you’ll want to create a separate property (as you have) and then populate the text field in your viewDidLoad method.

1 Like