我有一些代码可以更改UILabel
的文本,当应用程序第一次运行时它可以正常工作但是当我关闭它(应用程序转到后台)然后我重新打开它时,UILabel是nil
并且无法再次设置文字。
文本设置为viewDidLoad()
函数中的UILabel,我在viewDidLoad()
函数中调用applicationWillEnterForeground
将文本再次设置为UILabel
- 当它崩溃时错误fatal error: unexpectedly found nil while unwrapping an Optional value
。我调试了它,nil
找到的是UILabel
以下是AppDelegate.swift
中的一些代码:
func applicationWillEnterForeground(application: UIApplication) {
ViewController().refresh()
}
在ViewController.swift
:
func refresh() {
self.viewDidLoad()
}
当应用程序进入后台时,您对UILabel
成为nil
的原因有什么想法吗?
答案 0 :(得分:1)
不要试图从您的应用委托中保存对视图控制器的引用,而是让视图控制器订阅前台条目事件更好 -
在viewDidLoad
添加以下内容
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("enteringForeground:"),
name: UIApplicationWillEnterForegroundNotification, object: nil)
向ViewController添加一个函数
func enteringForeground(notification: NSNotification) {
// Whatever you need to do to refresh UI
// DO NOT CALL viewDidLoad
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}