【问题标题】:Swift UILabel is nil (error) when app goes in background当应用程序进入后台时,Swift UILabel 为零(错误)
【发布时间】:2014-11-23 23:21:24
【问题描述】:

我有一些代码可以更改 UILabel 的文本,当应用程序第一次运行时它工作正常但是当我关闭它(应用程序进入后台)然后我重新打开它时,UILabel 是 @987654323 @ 且文字无法再次设置。

文本在viewDidLoad() 函数中设置为UILabel,我在applicationWillEnterForeground 函数中调用viewDidLoad() 以再次将文本设置为UILabel - 那是它崩溃并给出错误fatal error: unexpectedly found nil while unwrapping an Optional value 的时候。我调试了一下,发现nilUILabel

这是AppDelegate.swift中的部分代码:

func applicationWillEnterForeground(application: UIApplication) { 
     ViewController().refresh() 
}

ViewController.swift:

func refresh() {
    self.viewDidLoad()
}

您知道为什么当应用程序进入后台时UILabel 变成nil

【问题讨论】:

  • 你永远不应该显式调用viewDidLoad viewWillAppear 等。你是如何在applicationWillEnterForeground 中获得对视图控制器的引用?请在此方法中显示代码
  • 这里是函数func applicationWillEnterForeground(application: UIApplication) { ViewController().refresh() },在ViewController中:func refresh() { self.viewDidLoad() }
  • 看起来您正在创建一个新的ViewController,而不是获取对现有的引用。这可以解释为什么你的标签是nil
  • 我想了解ViewController是如何获取它的值的(顺便说一下应该是viewController——变量以小写字母开头,类以大写字母开头)——我怀疑@的内容987654346@ 是一个没有被你的故事板实例化的实例,所以你的 IBOutlets 得到 nil
  • 我建议您不要这样做。您的视图控制器应该订阅在您的应用程序激活时发布的事件 - stackoverflow.com/questions/26680287/…

标签: ios iphone swift uilabel viewdidload


【解决方案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)

}

【讨论】:

  • 你应该在视图控制器被释放之前移除观察者。来自 NSNotificationCenter 文档:“在释放 addObserverForName:object:queue:usingBlock: 指定的任何对象之前,您必须调用 removeObserver:removeObserver:name:object:。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多