Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding convenience init

Tags:

swift

Trying to subclass an NSTextView:

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

I get this error: Must call a designated initializer of the superclass 'NSTextView' on this line: super.init(frame: frameRect).

According to the docs Convenience initializers must call another initializer available in the same class.. See 'Initializer Chaining' below: https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_286

But for NSTextViews the only designated inits i get are super.init(frame:, textContainer:) & super.init(coder: coder) & super.inti(). init(frame:) does some setup which I'd rather not implement myself.

Is there some way to use a super class's convenience initializer?

like image 200
Alex Marchant Avatar asked Mar 20 '23 08:03

Alex Marchant


1 Answers

Override the designated initialisers:

class MyTextView : NSTextView {

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

        setup();
    }

    func setup() {
         ...       
    }
}

var textView = MyTextView(frame: NSRect())

Since all the designated initialisers are overridden, all convenience will be automatically inherited.

There are two other designated initialzers to override:

init() {
}

and

init(coder:) {
}
like image 57
Sulthan Avatar answered Mar 28 '23 09:03

Sulthan