gpt4 book ai didi

swift - 在应用程序启动时将对象传递给 NSViewController 的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-28 06:29:03 24 4
gpt4 key购买 nike

在我的AppDelegateapplicationDidFinishLaunching 中,我需要使用从磁盘读取的数据创建一个对象,然后将该对象传递给初始 View Controller 以进行显示。执行此操作的最佳方法是什么?

现在我正在像这样以编程方式加载 Storyboard:

func applicationDidFinishLaunching(_ aNotification: Notification) {
importantThing = ImportantThing()
importantThing.load(url: URL(fileURLWithPath: "..."))

let storyboard = NSStoryboard(name: "Main", bundle: nil)
myWindowController = storyboard.instantiateController(withIdentifier: "MyWindowController") as! NSWindowController
(myWindowController.contentViewController as? MyViewController)?.importantThing = importantThing
myWindowController.showWindow(self)
}

但这感觉很笨拙。其一,该属性是在 viewDidLoad 之后设置的,所以现在 View 设置很奇怪。

一定有更好的方法来做到这一点。如果可能的话,我不想诉诸于使用单例,因为我实际上需要设置一些相互关联的对象(两个具有重要状态的对象相互引用,但包含其他)。解决这个问题的好方法是什么?

最佳答案

您在应用委托(delegate)中所做的是正确的。至于您应该在 View Controller 中做什么,Apple 的 Master-Detail 应用程序模板向您展示了正确的模式(我添加了一些评论):

// the interface
@IBOutlet weak var detailDescriptionLabel: UILabel!

// the property
var detailItem: NSDate? {
didSet {
self.configureView()
}
}

func configureView() {
// check _both_ the property _and_ the interface
if let detail = self.detailItem { // property set?
if let label = self.detailDescriptionLabel { // interface exists?
label.text = detail.description
}
}
}

override func viewDidLoad() {
super.viewDidLoad()
// at this point, its _certain_ that the interface exists
self.configureView()
}

如果您考虑一下,您会发现界面已正确更新无论事件的顺序如何 — 也就是说,无论 viewDidLoad 还是设置属性(property)是第一位的。只需遵循该模式即可。

关于swift - 在应用程序启动时将对象传递给 NSViewController 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40922825/

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