Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

ios - Subclassing NSObject in Swift - Best Practice with Initializers

Here is the layout of an example Class, can someone guide me on what's best practice when creating a subclass of NSObject?

class MyClass: NSObject {

    var someProperty: NSString! = nil

    override init() {
        self.someProperty = "John"
        super.init()
    }

    init(fromString string: NSString) {
        self.someProperty = string
        super.init()
    }

}

Is this correct, am I following best practice here?

I wonder if I'm correctly setting up the initializers (one that sets the string to a default, and one which I can pass in a string)?

Should I call super.init() at the end of each of the initializers?

Should my more specific (the one that takes a string) initializer simply call self.init() at the end rather than super.init()?

What is the right way to set up the initializers in Swift when subclassing NSObject? - and how should I call the super init ?

This question (albeit in Objective C) suggests you should have an init, which you always call and simply set the properties in more specific inits: Objective-C Multiple Initialisers

question from:https://stackoverflow.com/questions/25343330/subclassing-nsobject-in-swift-best-practice-with-initializers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not Swift ninja but I would write MyClass as:

class MyClass: NSObject {
    
    var someProperty: NSString // no need (!). It will be initialised from controller 
    
    init(fromString string: NSString) {
        self.someProperty = string
        super.init() // can actually be omitted in this example because will happen automatically.
    }
    
    convenience override init() {
        self.init(fromString:"John") // calls above mentioned controller with default name
    }        
}

See the initialization section of the documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...