Reputation: 1035
I have some outlets in my view and I try to edit them programatically in a function.
Xcode says:
unexpectedly found nil while unwrapping an optional value
However, when I edit outlets in viewDidLoad()
just after super.viewDidLoad()
, it works like a charm.
With the function :
func test(){
localDeviceNameView.stringValue = "some stuff" //Found nil here
}
With viewDidLoad
:
override func viewDidLoad() {
super.viewDidLoad()
localDeviceNameView.stringValue = "some stuff" //Works well
}
How can I make it work?
Upvotes: 1
Views: 459
Reputation: 540
You can use didSet on your variable. Like this :
@IBOutlet var localDeviceNameView : UIView! {
didSet {
localDeviceNameView.stringValue = "some stuff"
}
}
What's good with this approach is that you set your stringValue only when the localDeviceNameView
is set, which is right when it has been loaded from the NIB/Storyboard.
I think this is exactly what you need.
Upvotes: 3
Reputation: 1054
You are trying to call test()
before views are completely loaded, so they are not exist yet. Do it this way:
class MyController: UIViewController {
var something = ""
override viewDidLoad() {
super.viewDidLoad()
localDeviceNameView.stringValue = something
}
}
Or call you'r test()
method only if you sure than all views are loaded (viewDidLoad()
was called)
Upvotes: 1