我对UIViewController
中的以下情况感到非常困惑:
我有以下@IBOutlet
在我的故事板中有一个引用插座。
class MainViewController: UIViewController {
@IBOutlet weak var warningLabel: UILabel!
}
然后我在我的AppDelegate
:
var mainViewController: BLEMainViewController?
func applicationDidBecomeActive(application: UIApplication) {
let mainViewController: MainViewController = mainStoryboard.instantiateViewControllerWithIdentifier("mainViewController") as MainViewController
let viewController = UINavigationController(rootViewController: mainViewController)
mainViewController.didBecomeActive()
}
当我在didBecomeActive()
self.warningLabel.text = "something"
我收到以下错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
但如果我在里面执行以下操作,它可以正常工作:
override func viewWillAppear(animated: Bool) {
self.warningLabel.text = "something"
}
如果我warningLabel.text = "something"
我收到同样的错误。
如果我warningLabel?.text = "something"
它实际上没有设置。
如果我self.warningLabel?.text = "something"
它实际上没有设置。
究竟我究竟做错了什么?
修改
通过在我的UIViewController
中添加以下内容来修复:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActive", name: UIApplicationDidBecomeActiveNotification, object: nil)
然后,当设备变为活动状态时,它会执行didBecomeActive()
功能。
答案 0 :(得分:1)
IBOutlet
的{{1}}尚未在applicationDidBecomeActive
结束时初始化。因此,您尝试访问未初始化的对象的属性(.text
)。这会导致错误。
调用warningLabel?.text = "something"
时没有任何错误,因为?
表示只有在.text
初始化时才要访问warningLabel
属性(与{不同} {1}})。这也解释了为什么在这种情况下没有设置文本。
初始化插座属性的好地方在nil
的{{1}}功能中。此时,您的插座将被初始化。
答案 1 :(得分:0)
通过在我的UIViewController
中添加以下内容来修复:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActive", name: UIApplicationDidBecomeActiveNotification, object: nil)
然后,当设备变为活动状态时,它会执行didBecomeActive()
功能。