[英]NSWindowController designated initializer puzzle
I'm trying to make this code work: 我正在尝试使这段代码工作:
class MyWindowController: NSWindowController
{
let thing: Thing
convenience init(thing: Thing)
{
self.thing = thing
super.init(windowNibName: NSNib.Name(rawValue: "MyNib"))
}
}
The problem, of course, is that a convenience initializer can't call init
from a superclass. 当然,问题是便捷初始化器不能从超类调用
init
。 So how do I initialize my thing
and still be able to call init(windowNibName:)
, which is itself a convenience initializer? 那么如何初始化我的
thing
并仍然能够调用init(windowNibName:)
,它本身就是一个方便的初始化器? I'd rather not have to re-implement the nib loading myself, but how do I avoid it if I can only use designated initializers? 我宁愿不必重新实现自己的nib加载,但如果我只能使用指定的初始化器,我该如何避免呢?
According to the NSWindowController
documentation: 根据
NSWindowController
文档:
You can also implement an
NSWindowController
subclass to avoid requiring client code to get the corresponding nib's filename and pass it toinit(windowNibName:)
orinit(windowNibName:owner:)
when instantiating the window controller.您还可以实现
NSWindowController
子类,以避免要求客户端代码获取相应的nib文件名,并在实例化窗口控制器时将其传递给init(windowNibName:)
或init(windowNibName:owner:)
。 The best way to do this is to overridewindowNibName
to return the nib's filename and instantiate the window controller by passingnil
toinit(window:)
.执行此操作的最佳方法是覆盖
windowNibName
以返回nib的文件名,并通过将nil
传递给init(window:)
来实例化窗口控制器。 Using the init(window:) designated initializer simplifies compliance with Swift initializer requirements.使用init(window :)指定的初始化程序简化了对Swift初始化程序要求的遵从性。
You can implement your class as: 您可以将您的类实现为:
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")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.