gpt4 book ai didi

ios - 为什么在 App Delegate 中调用 viewdidload 时所有 IBOutlet(s) 都为 nil?

转载 作者:搜寻专家 更新时间:2023-10-31 22:31:19 24 4
gpt4 key购买 nike

我的 Xcode 调试器报告,除了 all the IBOutlets 发现 nil(myLine 等)外,所有其他值包括 alive(bool 值)都已设置。顺便说一句,当我删除 App Delegate 中的所有代码时一切正常,但我需要此 View 经常更新,因此有必要在 applicationWillEnterForeground 中实现它。另一件值得指出的事情是,在配置 View 1 和 2 中,我设置了每个 socket 的值。并且我在此之前让应用程序委托(delegate)调用 viewdidload 方法,因此所有 socket 都应该已经与代码连接,所以这些 socket 不应该为零。

An error message in the debugger -- fatal error: unexpectedly found nil while unwrapping an Optional value

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"
}
}

应用委托(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()
}

最佳答案

由于您正在 applicationWillEnterForeground 中使用默认初始化程序而不是从 Storyboard创建 两个 ViewController 的新实例,因此 IBOutlets 将被设置。您需要更新屏幕上的 View Controller 的当前实例。

与其从 appDelegate 执行此操作,不如让您的 View Controller 订阅 UIApplicationWillEnterForegroundNotification NSNotification 并在本地处理刷新可能更容易.这样你就不需要紧密耦合你的应用程序委托(delegate)和你的 View Controller ,你也不需要担心 View Controller 当前不在屏幕上:

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)
}

关于ios - 为什么在 App Delegate 中调用 viewdidload 时所有 IBOutlet(s) 都为 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com