在Swift中,init(windowNibName)只能作为一个方便的初始化器,NSWindowController的指定的初始化器是init(window),它显然需要我在一个窗口中传递。
我不能调用super.init(windowNibName)从我的子类,因为它不是指定的初始化,所以我显然必须实现方便init(windowNibName),这反过来需要调用self.init(window)。但如果我有我的nib文件,如何访问nib文件的窗口发送到该初始化程序?
// this overrides none of designated initializers class MyWindowController: NSWindowController { override func windowDidLoad() { super.windowDidLoad() } } // this one overrides all of them // // Awkwardly enough,I see only two initializers // when viewing `NSWindowController` source from Xcode,// but I have to also override `init()` to make these rules apply. // Seems like a bug. class MyWindowController: NSWindowController { init() { super.init() } init(window: NSWindow!) { super.init(window: window) } init(coder: NSCoder!) { super.init(coder: coder) } override func windowDidLoad() { super.windowDidLoad() } } // this will work with either of the above let mwc: MyWindowController! = MyWindowController(windowNibName: "MyWindow")
这在语言指南中的“初始化/自动初始化器继承”中介绍:
However,superclass initializers are automatically inherited if certain conditions are met. In practice,this means that you do not need to write initializer overrides in many common scenarios,and can inherit your superclass initializers with minimal effort whenever it is safe to do so.
Assuming that you provide default values for any new properties you introduce in a subclass,the following two rules apply:
Rule 1
If your subclass doesn’t define any designated initializers,it automatically inherits all of its superclass designated initializers.Rule 2 If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1,or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.