How to call an Objective-C singleton from Swift?

后端 未结 3 1869
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 07:48

I have an objective-C singleton as follows:

 @interface MyModel : NSObject
    + (MyModel*)   model;
    ...


        + (MyModel*) model 
        {
                     


        
3条回答
  •  没有蜡笔的小新
    2021-02-20 08:02

    Do exactly what the compiler warning tells you to:

    MyModel().someMethod()
    

    Read on to see why...


    Swift automatically recognizes ObjC conventions for initializers and convenience constructors. If you have a class that looks like this:

    @interface XYZThing : NSObject
    + (instancetype)thing;
    + (instancetype)thingWithFoo:(int)foo bar:(int)bar;
    @end
    

    ...then, when Swift turns them into initializers, it elides the part of the method name that's the generic name of the class (Thing/thing), moves the part of the selector that refers to the parameter to be a parameter label, and drops any prepositions connecting those parts. So the initializer declarations look like this in Swift:

    class XYZThing: NSObject [
        init()
        init(foo: Int, bar: Int)
    }
    

    and you construct objects like this:

    let thing = XYZThing()
    let otherThing = XYZThing(foo:3, bar:7)
    

    A followup: because class methods like +[XYZThing thing] are treated like initializers by the ObjC to Swift translator (even if that doesn't seem to fully work right now), that naming pattern is a bad idea for singletons. A singleton retrieval method shouldn't be an initializer, because an initializer always creates a new instance.

    A singleton retrieval method should instead have a name that doesn't start with the generic name of the class; e.g. +sharedThing, +defaultThing, +oneThingToRuleThemAll, etc.

提交回复
热议问题