gpt4 book ai didi

ios - 变量已设置但打印出 nil

转载 作者:行者123 更新时间:2023-11-28 12:17:57 24 4
gpt4 key购买 nike

我正在另一个 View Controller 中设置一个变量,它在 didSet 中工作,但在 viewdidload 中它打印出 nil

View Controller 1

    let methodView = MethodViewController()
methodView.items = itemsSelected
presentDetail(newVC)

View Controller 2

class MethodViewController: UIViewController {

var items: [[String: Any]]? {
didSet {
print(items) // PRINTS OUT ITEMS NORMALLY
}
}

override func viewDidLoad() {
super.viewDidLoad()

print(items) // PRINTS OUT NIL
}
}

最佳答案

它返回 nil,因为您正在使用一个实例设置项目,并且当您呈现屏幕并显示您的 methodViewController 时。然后你传递一个新的实例。而是使用您用来展示 Controller 的同一实例来设置项目

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.

let methodView = StackProgramViewController() //instance 1 //your case methodView
methodView.items = itemsSelected //value is set and printed


}


@IBAction func present(_ sender: Any) {

let newVc = self.storyboard?.instantiateViewController(withIdentifier: "stack") as! StackProgramViewController //instance 2 while presenting //your case newVc

newVc.items = itemsSelected //set value here with second instance nstaead of creating methodView
present(newVc, animated: true, completion: nil)

}

希望对你有帮助

关于ios - 变量已设置但打印出 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45830114/

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