【问题标题】:How to Implement Singleton class in Swift [duplicate]如何在 Swift 中实现单例类
【发布时间】:2016-02-18 22:01:56
【问题描述】:

我是 swift 编程新手,请告诉我如何使用代码在 swift 中实现单例类。

在 obj-c 中我知道

+ (id)sharedManager {
   static MediaModel *sharedMyManager = nil;
   static dispatch_once_t onceToken;

   dispatch_once(&onceToken, ^{
      sharedMyManager = [[self alloc] init];
   });
   return sharedMyManager;
}

在 swift 中怎么样

【问题讨论】:

标签: ios swift singleton


【解决方案1】:

在 Swift 中就是这么简单:

class YourClass {
    static let sharedInstance = YourClass()
}

并使用它:

YourClass.sharedInstance

【讨论】:

  • 谢谢老大!现在工作
【解决方案2】:

Swift 在单例类方面比 Obj-C 聪明得多。你可以这样声明;

final class MediaModel: NSObject {

    static let sharedMyManager = MediaModel()

    private override init() {
        super.init()
    }
}

然后调用它;

let sharedManager = MediaModel.sharedMyManager

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    相关资源
    最近更新 更多