【问题标题】:Overriding convenience init覆盖便利初始化
【发布时间】:2014-06-12 19:17:05
【问题描述】:

尝试继承一个 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.。请参阅下面的“初始化程序链接”: 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:) 做了一些我不想自己实现的设置。

有什么方法可以使用超类的便利初始化器吗?

【问题讨论】:

    标签: swift


    【解决方案1】:

    覆盖指定的初始化器:

    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:) {
    }
    

    【讨论】:

    【解决方案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")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2023-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多