可可 – 将Swift和init(windowNibName)中的NSWindowController子类化

可可 – 将Swift和init(windowNibName)中的NSWindowController子类化,第1张

概述我试图在Swift中启动一个基于Cocoa项目的新文档,并想创建一个NSWindowController的子类(如Apple的文档应用指南中所推荐的)。在ObjC中,你将创建一个NSWindowController子类的实例,发送initWithWindowNibName:消息,并相应地实现,调用superclasses方法。 在Swift中,init(windowNibName)只能作为一个方便 我试图在Swift中启动一个基于Cocoa项目的新文档,并想创建一个NSWindowController的子类(如Apple的文档应用指南中所推荐的)。在ObjC中,你将创建一个NSWindowController子类的实例,发送initWithWindowNibname:消息,并相应地实现,调用superclasses方法。

在Swift中,init(windowNibname)只能作为一个方便的初始化器,NSWindowController的指定的初始化器是init(window),它显然需要我在一个窗口中传递。

我不能调用super.init(windowNibname)从我的子类,因为它不是指定的初始化,所以我显然必须实现方便init(windowNibname),这反过来需要调用self.init(window)。但如果我有我的nib文件,如何访问nib文件的窗口发送到该初始化程序?

你需要覆盖NSWindowController(init(),init(window)和init(coder))的所有三个初始化器,或者不覆盖它们,在这种情况下,你的子类将自动继承init(windowNibname)你将能够使用超类的方便初始化构造它:
// this overrIDes none of designated initializersclass 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 abovelet 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.

总结

以上是内存溢出为你收集整理的可可 – 将Swift和init(windowNibName)中的NSWindowController子类化全部内容,希望文章能够帮你解决可可 – 将Swift和init(windowNibName)中的NSWindowController子类化所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1055966.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存