覆盖方便初始化方法

4

尝试对NSTextView进行子类化:

class MYTextView : NSTextView {
    init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        setup()
    }
}

我遇到了这个错误:Must call a designated initializer of the superclass 'NSTextView',出现在这一行:super.init(frame: frameRect)
根据文档,Convenience initializers must call another initializer available in the same class.。详见下面的“Initializer Chaining”章节: https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_286 但是对于NSTextViews,我只得到了三个指定初始化器:super.init(frame:, textContainer:)super.init(coder: coder)super.inti()。其中init(frame:)会进行一些设置,我不想自己实现。
有没有办法使用超类的方便初始化器?
2个回答

7

覆盖指定的初始化方法:

class MyTextView : NSTextView {

    init(frame frameRect: NSRect, textContainer aTextContainer: NSTextContainer!) {
        super.init(frame: frameRect, textContainer: aTextContainer)

        setup();
    }

    func setup() {
         ...       
    }
}

var textView = MyTextView(frame: NSRect())

既然所有指定的初始化器都已被覆盖,那么所有的便利初始化器都将自动继承。

还有两个其他的指定初始化器需要被覆盖:

init() {
}

并且

init(coder:) {
}

NSTextView实际上有init()init(coder:)需要被覆盖以继承方便的初始化。 - Alex Marchant
@AlexMarchant 已更新答案。 - Sulthan
@AlexMarchant 不得不查一下。init(coder:) 不是指定的,它实际上来自一个协议(NSCoding)。 - Sulthan
我猜这仍然算数,试着在 Playground 中尝试这些。使用 init(frame:,textContainer:) 会出现错误 https://gist.github.com/alexmarchant/3fd270471920af517908。加入 init() 仍然有错误 https://gist.github.com/alexmarchant/78dd4654115cad7c67b7。但是使用所有三个就可以了 https://gist.github.com/alexmarchant/d3dbe45563386db18ec6。 - Alex Marchant

2
我也刚刚被这个问题绊倒了。我仍然觉得使用继承进行Swift初始化很棘手,所以很可能我在这里还有其他地方没有理解对。
接受的答案似乎暗示着重写init(frame: textContainer:)initinit(coder:)会使init(frame:)可访问,但对我来说并没有起作用。
我唯一能够按照我想要的方式使事情正常工作的方法是这样的:
override init(frame frameRect: NSRect, textContainer container: NSTextContainer?) {
    super.init(frame: frameRect, textContainer: container)

    setup()
}

override init(frame frameRect: NSRect) {
    // this will end up calling init(frame:textContainer:)
    super.init(frame: frameRect)
}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接