应用程序进入后台时,Swift UILabel为nil(错误)

时间:2014-11-23 23:21:24

标签: ios iphone swift uilabel viewdidload

我有一些代码可以更改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的原因有什么想法吗?

1 个答案:

答案 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)

}