objective-c - 如何从 Swift 调用 Objective-C 单例?

标签 objective-c swift

我有一个 Objective-C 单例,如下所示:

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


        + (MyModel*) model 
        {
            static MyModel     *singlton = nil;
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^ {
                singlton = [[MyModel alloc] initSharedInstance];
            });
            return singlton;
        }


        - (MyModel*) initSharedInstance
        {
            self = [super init];
            if (self)
            etc.
        }

它在 GUI 代码中的多个位置被调用为:

[[MyModel model] someMethod];

因此,无论 GUI 的哪个部分碰巧首先引用它,模型都会被创建。

我不确定如何在 Swift 中实现通过 [[MyModel model] someMethod] 访问类的等价物,因为使用 Swift 的所有示例都涉及使用初始化程序创建对象以及何时将 Objective C 类方法代码转换为Swift 初始化代码有一个问题,当方法没有参数时它无法工作。

最佳答案

更新 ++++++++++

仅当您使用从类名后缀派生的名称命名单例方法时,才需要下面的变通方法,即 OP 问题方法名称是模型并且类称为 MyModel。

如果该方法被重命名为类似于单例的东西,那么就可以像这样从 Swift 中调用它:

  let m  = MyModel.singleton()

+++++++++++

我不知道这是好还是坏的做法,但我能够通过添加虚拟 init 方法解决没有参数时初始化器转换不起作用的问题。因此,以其他答案中的代码为例:

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

@implementation XYZThing
+ (XYZThing*) thing
{
    NSLog(@"This is not executed");
    return nil;
}

+ (XYZThing*)thingWithFoo:(int)foo bar:(int)bar
{
    NSLog(@"But this is");
    return nil;
}
@end


...

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

上面这段代码没有调用 thing 方法,但是调用了 thingWithFoo:bar: 方法。

但是如果它被更改为这个那么现在 thing 方法将被调用:

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


    @implementation XYZThing

    + (XYZThing*) init
    {
         return nil;
    }
    + (XYZThing*) thing
    {
        NSLog(@"Now this is executed");
        return nil;
    }

    + (XYZThing*)thingWithFoo:(int)foo bar:(int)bar
    {
        NSLog(@"And so is this");
        return nil;
    }
    @end


...

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

关于objective-c - 如何从 Swift 调用 Objective-C 单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24148464/

相关文章:

swift - Swift Playground 中的 NSTimer.scheduledTimerWithTimeInterval

ios - 使用 Coredata 学习 Swift : why don't I get any UITableViewCells?

objective-c - iOS无法播放我的声音?

ios - 在 iOS Swift 中以编程方式移动 UIView

swift - 核心数据保存在哪里?

iphone - 游戏设计 : Checking for object intersection or getting values from accelerometer

ios - xcode swift AnyObject 到 Swift 转换

ios - 在 Swift 中使用 CFReadStreamCreateWithFTPURL 测试 FTP 连接

objective-c - 从另一个类访问 TableViewController

objective-c - 缩放黑白图像