为什么在App Delegate中调用viewdidload时,所有IBOutlet都找到了nil?

时间:2016-07-22 01:55:07

标签: ios swift debugging delegates

我的Xcode调试器报告,除了所有IBOutlets 找到nil(myLine等)之外,其他所有值都包括alive(bool值)。顺便说一下,当我删除App Delegate中的所有代码时,一切都有效,但我需要经常更新此视图,因此在applicationWillEnterForeground中实现它是必要的。另外值得指出的是,在配置视图1和2中,我设置了每个插座的值。在此之前我使用app delegate调用viewdidload方法,所以所有的出口都应该已经与代码连接,所以这些出口不应该是零。

  

调试器中的错误消息 - 致命错误:意外发现nil   同时展开一个可选值

import UIKit

class ViewController: UIViewController {

    var alive : Bool = true
    var aliveDefault = NSUserDefaults.standardUserDefaults()


    //IBOulet Connections

    @IBOutlet weak var myLine: UILabel!

    @IBAction func buttontapped(sender: AnyObject) {
        alive = false
        NSUserDefaults.standardUserDefaults().setObject(alive, forKey: "alive")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        loadView()
    }
    func loadView(){
         alive = aliveDefault.boolForKey("alive")
         if alive = true {
            configureView()
          }else{
            configureView2()
        }
    }

    func configureView(){
        myLine.text = "Random text"
    }

    func configureView2(){
        myLine.text = "Random text 2"
    }
}

App Delegate

func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    ViewController().viewDidLoad()
    ViewController().configureView()
}

2 个答案:

答案 0 :(得分:3)

由于您使用默认初始值而非故事板在ViewController中创建两个 applicationWillEnterForeground新实例,因此不会设置IBOutlets 。您需要更新屏幕上视图控制器的当前实例。

您可以更轻松地让视图控制器订阅appDelegate UIApplicationWillEnterForegroundNotification并在本地处理刷新,而不是从NSNotification执行此操作。这样您就不需要将应用程序委托和视图控制器紧密耦合,如果视图控制器当前不在屏幕上,您也不必担心:

class ViewController: UIViewController {

    ...

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.loadView), name: UIApplicationWillEnterForegroundNotification, object: nil)
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

答案 1 :(得分:0)

在为IBOutlets分配值之前执行ViewController.loadViewIfNeeded()