gpt4 book ai didi

swift - NSWindowController 指定初始化器之谜

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

我正在努力使这段代码工作:

class MyWindowController: NSWindowController
{
let thing: Thing

convenience init(thing: Thing)
{
self.thing = thing

super.init(windowNibName: NSNib.Name(rawValue: "MyNib"))
}
}

当然,问题在于便利初始化程序无法从父类(super class)调用 init。那么如何初始化我的 thing 并且仍然能够调用 init(windowNibName:),它本身就是一个便利的初始化器?我宁愿不必自己重新实现 nib 加载,但如果我只能使用指定的初始化器,我该如何避免呢?

最佳答案

根据 NSWindowController 文档:

You can also implement an NSWindowController subclass to avoid requiring client code to get the corresponding nib's filename and pass it to init(windowNibName:) or init(windowNibName:owner:) when instantiating the window controller. The best way to do this is to override windowNibName to return the nib's filename and instantiate the window controller by passing nil to init(window:). Using the init(window:) designated initializer simplifies compliance with Swift initializer requirements.

您可以将您的类实现为:

class MyWindowController: NSWindowController
{
let thing: Thing

override var windowNibName: NSNib.Name? {
return NSNib.Name(rawValue: "MyNib")
}

init(thing: Thing) {
self.thing = thing

super.init(window: nil)
}

required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

关于swift - NSWindowController 指定初始化器之谜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51294747/

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