The issue is likely that the outlets have not been hooked up by the time you set page
, and if these outlets are implicitly unwrapped optionals (with the !
after the type name, e.g. UILabel!
), that will result in the error you describe. This problem will manifest itself if, for example, you set page
before the view controller in question has been presented and all of the outlets have been hooked up.
So, I’d recommend:
Use optional chaining with your @IBOutlet
references so it won’t fail if the outlets haven’t been hooked up yet.
Go ahead and keep your didSet
observer on page
, if you want, but make sure you also update the controls in viewDidLoad
in case page
was set before the outlets were hooked up.
For example:
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var imageView: UILabel!
@IBOutlet weak var ingredientLabel: UILabel!
@IBOutlet weak var instructionLabel: UILabel!
var page: Page? { didSet { updateControls(for: page) } }
override func viewDidLoad() {
super.viewDidLoad()
updateControls(for: page)
}
func updateControls(for page: Page?) {
nameLabel?.text = page?.dishName
imageView?.image = page.flatMap { UIImage(named: $0) }
ingredientLabel?.text = page?.ingredient
instructionLabel?.text = page?.instruction
}
Note, you only need this didSet
observer if the page
might be set (again) after the view has been presented. If not, the didSet
observer is not needed.