3

I'd like to set text value of UITextField (IBOutlet) in the DidSet of my model object that I pass.

Here the code:

    let manageSettingViewController: ManageSettingViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ManageSettingViewController") as ManageSettingViewController
    self.navigationController?.pushViewControllerCustom(manageSettingViewController)
    manageSettingViewController.setting = setting

And in the didSet of manageSettingViewController:

   var setting: Setting? {
    didSet
    {
        keyTextField.text = setting?.label
        valueTextField.text = setting?.value
    }

How can I set the text? Because in this case Xcode crash because "keyTextField is nil" :(

1 Answers1

3

You're setting manageSettingViewController.setting right after instantiating manageSettingViewController -- at this point, it hasn't loaded its view from the nib/storyboard yet, so all of its IBOutlet variables (which presumably keyTextField and valueTextField are) are still nil. Those text fields are hooked up as of when ManageSettingViewController's viewDidLoad method is called.

You could change your didSet to check the optional outlets before setting them, or assign through optional chaining:

didSet {
    keyTextField?.text = setting?.label
    valueTextField?.text = setting?.value
}

This would avoid the crash, but it would also fail to change your text field's content. You'd have to also implement viewDidLoad for ManageSettingViewController to check its setting property and set its text fields accordingly.

Of course, that would duplicate the code from your didSet. That code might still be useful if you want to set setting from elsewhere and have the UI update automatically, but didSet won't help you for updating UI before the UI loads.

rickster
  • 124,678
  • 26
  • 272
  • 326
  • With objective c I often used this pattern. And to avoid duplicating code I added self.setting = self.setting in viewDidLoad to trigger the setter again. However, this isn't possible with swift anymore. Any idea for a workaround for this? – Frank Hartmann Jun 27 '15 at 17:02